2013-05-07 80 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++)