Reputation: 107
which is the correct procedure to find a datarow exists in datatable?
Running the below code is giving the following error:
"System.IndexOutOfRangeException: 'There is no row at position 99.
int myRowNumber = 99;
if (myDatatable.Rows[myRowNumber] == null)
{
MessageBox.Show("row does not exists");
return;
}
Upvotes: 0
Views: 4925
Reputation: 6977
int myRowNumber = 99;
if (!myDatatable.HasRowAt(myRowNumber))
{
MessageBox.Show("row does not exists");
}
You can create your own extension method for the data table and reuse it later in your code.
public static bool HasRowAt(this DataTable dt, int index)
{
return (dt.Rows.Count <= index) And (index >= 0);
}
Upvotes: 2
Reputation: 61
Maybe you can have a try on this?
if (myDatatable.Rows.Count > myRowNumber - 1)
{
MessageBox.Show("row exists");
return;
}
else
{
MessageBox.Show("row does not exists");
return;
}
Upvotes: 1
Reputation: 4883
How about using an if
condition?
if(myDatatable.Rows.Count <= myRowNumber)
{
MessageBox.Show("row does not exists");
}
else
{
MessageBox.Show("row exists");
}
Upvotes: 2