Check/Uncheck button check box

Asked

Viewed 133 times

1

In my program there is a button to mark and the same button to uncheck a checkbox.

Example: If I click once, it marks the check box, if I click again on the button it unchecks the check box. However, if you click again no longer mark the checkbox, after the second click the button loses the action.

Follows my code:

public frmLaudosPS()
{
    InitializeComponent();
    this.btn_seleciona.Click += this.marcar;
}

private void marcar(object sender, EventArgs e)
{
    DataTable table = (DataTable)dgw_laudos.DataSource;
    foreach (DataRow row in table.Rows)
        row["SELECIONAR"] = true;
    this.btn_seleciona.Click -= this.marcar;
    this.btn_seleciona.Click += this.desmarcar;
}

private void desmarcar(object sender, EventArgs e)
{
    DataTable table = (DataTable)dgw_laudos.DataSource;
    foreach (DataRow row in table.Rows)
        row["SELECIONAR"] = false;
}
  • 1

    The code of desmarcar. Without it it is impossible to help without being at the base of the kick.

  • Sorry I forgot the rest of the code, I already put the rest of the code. Vlw.

1 answer

4


Missing you remove and add the Handler in the uncheck event as well. Without this the code makes no sense.

private void desmarcar(object sender, EventArgs e)
{
    DataTable table = (DataTable)dgw_laudos.DataSource;
    foreach (DataRow row in table.Rows)
        row["SELECIONAR"] = false;

    this.btn_seleciona.Click -= this.desmarcar;
    this.btn_seleciona.Click += this.marcar;
}

Anyway, I think it would be much more interesting if you kept just one method. It makes no sense to keep the same code twice just to change the value of a boolean.

private void marcar_desmarcar(object sender, EventArgs e)
{
    DataTable table = (DataTable)dgw_laudos.DataSource;
    foreach (DataRow row in table.Rows)
        row["SELECIONAR"] = !Convert.ToBoolean(row["SELECIONAR"]);
}
  • Thanks for helping Linq, but because the button loses the action after the second click or after reschedule...

  • @Juniorguerreiro You saw the answer?

  • Yes I did and I’ve already adjusted the code and yet, when I click for the third time the button does nothing more..

  • @Juniorguerreiro In a little while I’ll take a test and see if it really happens

  • Vlw Thank you Linq...

  • @Juniorguerreiro I adjusted the answer with another alternative, I still could not do the test with handlers

  • Thank you very much Linq gave his change certificate, I left a single method.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.