Mark / Uncheck button check box

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 checkbox, if I click the button again it unchecks the check box. However, clicking again no longer marks the checkbox, after the second click the button loses the action.

Follow 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;
}
    
asked by anonymous 12.07.2018 / 20:03

1 answer

4

You still have to remove and add the handler in the uncheck event as well. Without it the code does not make 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 a lot more interesting to keep just one method. It does not make 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"]);
}
    
12.07.2018 / 20:46