Q:

How to Discard Null Values in Data Table when Checking with IF Condition inside a For Loop

In my Project I select the User ID based Upon some Condition from DB and save it in Datatable and checking it with the ID entered by the User based Upon Condition only 5 rows will be fetched but in the loop and in IF condition it is Checking with the 6th row which is null so it throws the Exception "There is no row at Position 6" My Code is  
protected void Button1_Click(object sender, EventArgs e)
 {
   SqlConnection con1 = new SqlConnection(@"Data Source=ESLHPC17\SQL2008;Initial Catalog=Eval;User ID=sa;Password=sa@123");         
    try
    {

     string qry = "Select Userid from Faculty where Flag='A'";
     SqlCommand cmd = new SqlCommand(qry,con1);
     con1.Open();
     SqlDataAdapter da = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da. Fill(dt);
     for (int x = 0; x <= dt. Rows. Count; x++)
     {
        //DataRow row = dt. Rows[i];
        //object ID = row[0];
        //if (ID ! = null && ! String. IsNullOrEmpty(ID.ToString().Trim()))
        dt. Select("Userid is Not Null");

        if (TextBox1.Text == dt. Rows[x]["Userid"].ToString())
        {
          lblMessage. Text = string. Empty;

          Panel1.Visible = true;

        }
        else
        {
          lblMessage. Visible = true;
          lblMessage. ForeColor = System. Drawing. Color. Red;

          lblMessage. Text = "Invalid Userid or UserId does not Exist in the Database !!!"; 
         }

    }

  }
 finally
 {
   con1.Close();
   con1.Dispose();
 }

}

A:

as index no.  starts from zero you should run your loop till total row count minus 1.In your case u have 5 rows so dt. Rows. Count will give you 5,loop is starting from starting index 0,so it will run till 5 if you write dt. Rows. Count,therefore you should  write dt. Rows. Count-1 so that loop runs till 5th row only,which is ultimately your last row with index 4
 for (int x = 0; x <= dt. Rows. Count-1; x++)

