Reputation: 438
In my form i've a tabpanel with five tab.
Every tab have a datagridview binded to a databes.
All datagrid are filled correctly,but the event CellContentClick
works only on the frist tab.
I'm trying to retrive content on selected cell with this code:
//fristtabpag and datagrid1
private void dgw1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
text1.Text = dgw1.SelectedRows[0].Cells[0].Value.ToString();
}
//second tabpag and datagrid1
private void dgw2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
text1.Text = dgw2.SelectedRows[0].Cells[0].Value.ToString();
}
//other....
And it works only on frist tabpage.
i use same code corrrectly fixed for other page, but i get an error for the index. How fix it?
Upvotes: 0
Views: 226
Reputation: 818
You could try using the DataGridViewCellEventArgs like this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
text1.Text = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.SafeToString();
}
Alternatively you could try using the CurrentCellChanged event and get the value from the CurrentCell property:
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
DataGridView dgv = sender as DataGridView;
if (dgv.CurrentCell != null)
{
text1.Text = ((DataGridView)sender).CurrentCell.Value.SafeToString();
}
}
(The method SafeToString() is a simple extensionmethod, all it does is check if the object is null before calling ToString(). If the object is null it returns an empty string)
From your code-example it looks like your eventhandlers does the same thing to different DataGridViews. By using the sender parameter, you can use the same handler for all the DataGridViews.
Upvotes: 1