OnClick event in WinForms DataGridView
-
24-09-2019 - |
Question
I am using DataGridView in WinForms and by this piece of code I am assigning it columns and values
dataGrid.DataSource = sourceObject;
only by this line all the columns and values into the grid. How do I handle the onClick event of a specific row or field. I want to do edit a particular item in the grid but I cannot find any way to send the id of an item from the event method.
There is class DataGridViewEventHandler which I do not understand?
I have also tried to add columns manually as a buttons but I did not find way to assign it action method onClick.
Solution
You cannot find "OnClick" event for cell inside DataGridView, as it does not exist. Have a look at MSDN Page for DataGridView Events provided for Cell Manipulation and Events
Here are some samples from MSDN, about the events which you may use
Sample CellMouseClick Event and Handler
private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e) {
System.Text.StringBuilder cellInformation = new System.Text.StringBuilder();
cellInformation .AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex );
cellInformation .AppendLine();
cellInformation .AppendFormat("{0} = {1}", "RowIndex", e.RowIndex );
cellInformation .AppendLine();
MessageBox.Show(cellInformation.ToString(), "CellMouseClick Event" );
}
Sample CellClick Event and Handler
private void dataGridView1_CellClick(object sender,
DataGridViewCellEventArgs e)
{
if (turn.Text.Equals(gameOverString)) { return; }
DataGridViewImageCell cell = (DataGridViewImageCell)
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Value == Play)
{
// PlaySomething()
}
else if (cell.Value == Sing)
{
// SingSomeThing();
}
else
{
MessagBox.Show("Please Choose Another Value");
}
}
Hope this helps
OTHER TIPS
Here
, you can see a list of events for the DataGridView. If you want to see if a cell has been clicked, you would want to consume the CellMouseclick
event. In your code, you can handle the event like this:
private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
{
//Do something
}
To get specific details about the cell, then you can use the 'e' property mentioned above. It's of type DataGridViewCellMouseEventArgs
. This will give you information about that specific cell. You can handle most of the other events, found in the first link, in the same way. (Not all the events will have DataGridViewCellMouseEventArgs
as the argument, of course).