2016-05-15 115 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(); 
} 
相关问题