Reputation: 69
Can anyone help me please?
I have to find the row number from 1 selected array which I stored in one separate array and randomly I'm trying to get the row number from datagridview
In other words: if I know a column value for a given row in a datagridview (e.g. for this row, FirstName == 'Bud'), how can I get the row ID?
Upvotes: 7
Views: 33452
Reputation: 1
//If U Have Add CheckBox To Ur Datagridview
int rowIndex = -1;
DataGridViewCheckBoxCell oCell;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
oCell = row.Cells[0] as DataGridViewCheckBoxCell;
bool bChecked = (null != oCell && null != oCell.Value && true == (bool)oCell.Value);
if (true == bChecked)
{
rowIndex = row.Index;
//ur code
}
}
Upvotes: 0
Reputation: 5165
From: http://www.vbforums.com/showthread.php?t=610134
Call the Find method of the BindingSource and it will return the index of the matching row if there is one. If there is, you index the BindingSource to get that row and update the appropriate fields. If there isn't, you call the AddNew method of the BindingSource to create a new row and set the appropriate fields.
Upvotes: 0
Reputation: 1858
You can use LINQ query:
int index = -1;
DataGridViewRow row = dgv.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells[columnId].Value.ToString().Equals("Some string"))
.First();
index = row.Index;
Upvotes: 18
Reputation: 55039
There's probably some easier way where you filter it in some way but at the moment I can only think of looping through it.
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
if(row.Cells(1).Value.ToString().Equals("mystr"))
{
rowIndex = row.Index;
break;
}
}
// rowIndex is now either the correct index or -1 if not found
Upvotes: 1