HelpNeeder
HelpNeeder

Reputation: 6490

How to delete or edit by using 2 check boxes in DataGridView?

I am displaying a data in DataGridView object. The first column represents a delete and second is edit as check boxes, the rest is data.

What I am trying to do is to do delete and edit to the selected data when one of the check boxes are selected.

I am stuck of how to do something when one of check boxes was selected, basically how to check which field was clicked.

How do I do this?

I have this which uncheck any other field checked earlier:

public MainWindow()
{
    InitializeComponent();

    dgvPC.CellContentClick += new DataGridViewCellEventHandler(ContentClick_CellContentClick);
}

void ContentClick_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    foreach (DataGridViewRow row in dgvPC.Rows)
    {
        row.Cells[Delete1.Name].Value = false;
        row.Cells[Edit1.Name].Value = false;
    }
}

I am adding data as such:

if (security.DecryptAES(read.GetString(1), storedAuth.Password, storedAuth.UserName) == "PC Password")
{
    // Count PC passwords.
    countPC++;

    dgvPC.Rows.Add(read.GetInt32(0), false, false, 
        security.DecryptAES(read.GetString(5), storedAuth.Password, storedAuth.UserName), 
        security.DecryptAES(read.GetString(6), storedAuth.Password, storedAuth.UserName));
}

Upvotes: 0

Views: 120

Answers (1)

V4Vendetta
V4Vendetta

Reputation: 38230

I infer from your statement that you are unable to identify which checkbox is being considered

So to narrow in you should attempt at using the CellValueChanged event of the grid

void grd_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
     if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
     {
          //Now you know its a checkbox
          //use the ColumnIndex of the CurrentCell and you would know which is the column
          // check the state by casting the value of the cell as boolean
     }
}

If you want the action to be immediate then you will have to commit the value and this happens when the focus moves out of the cell. Try handling CurrentCellDirtyStateChanged of the grid

Something like this should work for you

void grd_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (grd.IsCurrentCellDirty)
    {
        grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

Upvotes: 1

Related Questions