2016-05-15 52 views
0

我正在使用此代碼在使用C#代碼的SQL Server數據庫中進行搜索,但是當數據表爲null時出現錯誤。請幫我解決問題並找到解決方案。這是我的代碼:爲什麼datatable爲空時會出現錯誤?

private void button4_Click_1(object sender, EventArgs e) 
{ 
    DataTable dt = new DataTable(); 

    if (!string.IsNullOrEmpty(textBox1.Text)) 
    { 
     SqlConnection sqlconn = new SqlConnection(@"Data Source=.;Initial Catalog=ghale;Integrated Security=True"); 
     SqlDataAdapter sqlcmd = new SqlDataAdapter("select * from ranandeh WHERE [email protected]", sqlconn); 
     sqlcmd.SelectCommand.Parameters.AddWithValue("@ID", textBox1.Text); 

     dt.Clear(); 

     sqlcmd.Fill(dt); 

     if (dt!= null) 
     { 
      comboBox2.Text = dt.Rows[0]["name"].ToString(); 
     } 
    } 
} 

請參閱錯誤在下面的圖片:

enter image description here

+1

你能發佈完整的錯誤/堆棧跟蹤嗎?適用線路。 – Idos

+0

請訪問圖片 – user6313751

+0

發佈你得到的錯誤 – mohsen

回答

1

這是因爲你嘗試獲取不存在的,所以你必須檢查計數行的行的DataTable。

if (dt != null && dt.Rows.Count> 0) 
{ 
    comboBox2.Text = dt.Rows[0]["name"].ToString(); 
} 
相關問題