Murulimadhav
Murulimadhav

Reputation: 107

How to check if a datarow exists by row index?

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

Answers (3)

Ray Krungkaew
Ray Krungkaew

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

Levanan Gan
Levanan Gan

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

NicoRiff
NicoRiff

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

Related Questions