Reputation: 13843
With a listbox, I have the following code to extract the item selected:
private void inventoryList_SelectedIndexChanged(object sender, EventArgs e)
{
String s = inventoryList.SelectedItem.ToString();
s = s.Substring(0, s.IndexOf(':'));
bookDetailTable.Rows.Clear();
...
more code
...
}
I want to do something similar for a DataGridView, that is, when the selection changes, retrieve the contents of the first cell in the row selected. The problem is, I don't know how to access that data element.
Any help is greatly appreciated.
Upvotes: 3
Views: 26548
Reputation: 273
This is another way of approaching to this question using the column name.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{
if (e.ColumnIndex == dataGridView1.Columns["ColumnName"].Index)
{
var row = senderGrid.CurrentRow.Cells;
string ID = Convert.ToString(row["columnId"].Value); //This is to fetch the id or any other info
MessageBox.Show("ColumnName selected");
}
}
}
If you need to pass the data from that selected row you can pass it this way to the other form.
Form2 form2 = new Form2(ID);
form2.Show();
Upvotes: 0
Reputation: 1149
I think that this is what you're looking for. But if not, hopefully it will give you a start.
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
//User selected WHOLE ROW (by clicking in the margin)
if (dgv.SelectedRows.Count> 0)
MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());
//User selected a cell (show the first cell in the row)
if (dgv.SelectedCells.Count > 0)
MessageBox.Show(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());
//User selected a cell, show that cell
if (dgv.SelectedCells.Count > 0)
MessageBox.Show(dgv.SelectedCells[0].Value.ToString());
}
Upvotes: 15