SqlDataReader填充组合框IsDBNull问题

时间:2013-08-26 16:51:07

标签: c# sql sql-server winforms

您好我已尝试处理Null异常,但我仍然收到异常警告:data为null此方法或属性无法在空值上调用。

这是我的代码:

 spojeni.Open();
        string sql_combobox = "SELECT column FROM tableO RDER BY nazev ASC";
        SqlCommand combobox = new SqlCommand(sql_combobox, spojeni);


        try
        {
            SqlDataReader dr = combobox.ExecuteReader();
            while (dr.Read())
            {
                if (!dr.IsDBNull(0))
                {
                    comboBox1.Items.Add(dr["column"]);
                }
            }

            dr.Close();
            dr.Dispose();
            spojeni.Close();
        }

2 个答案:

答案 0 :(得分:1)

我从你的代码中得到的东西

spojeni.Open();
//change your query string there was an error in it
string sql_combobox = "SELECT column FROM table ORDER BY nazev ASC";
SqlCommand combobox = new SqlCommand(sql_combobox, spojeni);


try
{
   SqlDataReader dr = combobox.ExecuteReader();
   while (dr.Read())
   {
       if (!dr.IsDBNull(0))
       {
          comboBox1.Items.Add(dr.GetString(0));
       }
   }

   dr.Close();
   dr.Dispose();
   spojeni.Close();
}

答案 1 :(得分:0)

您需要指定要检查的列...尝试这样的事情:

if (dr["column"] != DBNull.Value)
{
    comboBox1.Items.Add(dr["column"]);
}