0

Hi below I represented the structure of my current datagridview, the last field of the datagriview has a checkbox what I have to do is retrieve the id of the row corresponds when the check is made is true, how can I do to do this?

DataGridView Structure:

MyId | My Value | checkbox

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
riki
  • 1,502
  • 5
  • 17
  • 45

2 Answers2

0

If you want to get the Id of the Selected row or cell, then it's pretty straight forward as @JohnG commented.

Otherwise, if you're not on any selection row or cell, then you can iterate over the DataGridView and locate it using

string checkBoxColumnName = "IsMale"; // CheckBox column name
string outputColumnName = "MyId"; // Cell column name you want to value from.

var headerColumn = dataGridView1.Columns.Cast<DataGridViewColumn>().Single(c => c.Name == checkBoxColumnName);

var r = dataGridView1.Rows.Cast<DataGridViewRow>().FirstOrDefault(row => (bool)(row.Cells[headerColumn.Index].Value));
var result = r.Cells[outputColumnName].Value.ToString(); // result as string
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

This is one way to retrieve ID you will have to use the cellValueChanged property to retrieve checked row ID

 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
           if (Convert.ToBoolean(dataGridView1.CurrentRow.Cells[2]) == true)
                {
                    textbox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                }
        }
Abrar
  • 11
  • 5