2013-05-07 78 views
2

在我的项目中,我选择基于来自数据库的某个条件的用户ID并将其保存在数据表中,并使用用户输入的ID进行检查一旦条件只有5行会,但在循环和IF条件它与第6行是空,因此它抛出异常检查中获取“没有排在第6位”我的代码是如何在For循环中使用IF条件进行检查时在数据表中丢弃空值

protected void Button1_Click(object sender, EventArgs e) 
{ 
    SqlConnection con1 = new SqlConnection(@"Data Source=ESLHPC17\SQL2008;Initial Catalog=Eval;User ID=sa;[email protected]");   
    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(); 
} 

}

回答

2

作为索引号。从零开始,你应该运行循环,直到总行数减1.在你的情况下,你有5行,所以dt.Rows.Count会给你5,循环从开始索引0开始,所以它会运行到5,如果你写dt.Rows.Count,因此,你应该写dt.Rows.Count-1,以便循环运行,直到只有5行,这是最终的最后一行指数4

for (int x = 0; x <= dt.Rows.Count-1; x++) 
+0

感谢十亿工作... – Rajesh 2013-05-07 10:11:27

+0

好,我的荣幸,好,接受答案,如果它为你工作rajesh – Anuj 2013-05-07 10:12:18

1

你有index少了一个那么rows因此改变循环条件。行集合是基于零的索引,第一个元素位于零索引处,最后一行位于索引1处,小于行数。

变化

for (int x = 0; x <= dt.Rows.Count; x++) 

for (int x = 0; x < dt.Rows.Count; x++) 

可以过滤行的行其中userid不为空使用Select

+0

谢谢十亿它工作... – Rajesh 2013-05-07 10:10:11

0

改变你的for循环如下

for (int x = 0; x < dt.Rows.Count; x++) 

,改变你的SQL如下

string qry = "Select Userid from Faculty where Flag='A' and Userid is Not Null"; 

你不需要通过代码来执行用户ID检查

0

请将查询变为此

从学院中选择用户ID,其中标志= 'A' 和用户ID IS NOT NULL

1

要么改变你的for条件for (int x = 0; x < dt.Rows.Count; x++)或使用foreach

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); 
     foreach (DataRow dc in dt.Rows) 
     { 
      if (TextBox1.Text == dc["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(); 
    } 
0

要么使用

for (int x = 0; x < dt.Rows.Count; x++) 

for (int x = 0; x <= dt.Rows.Count-1; x++)