C# – Getting data from selected datagridview row and which event

cdatagridviewwinforms

I have a DataGridView (Selectionmode: FullRowSelect) on a windows form along with some textboxes, so what i want to do is that whenever a user selects a row(click or double_click maybe), the contents of that row must be displayed in the text boxes,

i tried out this codes

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show("CEll Double_Click event calls");
    int rowIndex = e.RowIndex;
    DataGridViewRow row = dataGridView1.Rows[rowIndex];
    textBox5.Text = row.Cells[1].Value;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    int rowIndex = e.RowIndex;
    DataGridViewRow row = dataGridView1.Rows[rowIndex];
    textBox5.Text = dataGridView1.Rows[1].Cells[1].Value.ToString();// row.Cells[1].Value;
}

there are many other textboxes, but the main problem is that none of the event seems to be triggered, what event should i use to do so, or is there some property of datagrid that i might have set wrong?
Any help would be appreciated…:(

Best Answer

You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{
    foreach (DataGridViewRow row in dataGridView.SelectedRows) 
    {
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();
        //...
    }
}

You can also walk through the column collection instead of typing indexes...

Related Topic