I want to get value of row where checkbox is checked. I am new to C# windows forms and so far unsuccessful. I want to eventually use these row values, so if user selects multiple row and then I should get value for those checked. Also, I have set the selection mode to 'fullrowselect'
Please suggest changes to my code
private void button1_Click(object sender, EventArgs e)
{
StringBuilder ln = new StringBuilder();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (dataGridView1.SelectedRows.Count>0 )
{
ln.Append(row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("No row is selected!");
break;
}
}
MessageBox.Show("Row Content -" + ln);
}
Having a check-box column in your grid will not change the internal status of any of the rows, so you will need to iterate over them all yourself to evaluate. This should do the trick, although you will need to provide the correct column index for the checkbox column in checkBoxColumnIndex
int checkBoxColumnIndex = nnn; // 0 based index of checkboxcolumn
private void button1_Click(object sender, EventArgs e)
{
List<string> checkedItems = new List<string>();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell checkBox= row.Cells[checkBoxColumnIndex] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(checkBox.Value) == true)
{
checkedItems.Add(row.Cells[1].Value.ToString());
}
}
if (checkItems.Count > 0)
MessageBox.Show("Row Content -\r\n" + String.Join("\r\n", checkedItems));
else
MessageBox.Show("No row is selected!");
}
Admittedly, the List<string>
is a heavy construct if all you want to do is print the list, but it would be useful if you need to do further processing on all of the checked values.