【问题标题】:Data is Null. This method or property cannot be called on null values.(using combo box)数据为空。不能对空值调用此方法或属性。(使用组合框)
【发布时间】:2014-07-04 22:26:44
【问题描述】:

您好,我将用于填充组合框的表中有空值。我不知道该怎么做。当我运行下面的代码时,我得到了错误:

数据为空。不能对空值调用此方法或属性。

我需要帮助,我是 mysql 新手

代码:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string constring = "datasource=localhost;port=3306;username=root;password=root";
    string Query = "SELECT * from database.check WHERE patientname IS NOT NULL";
    MySqlConnection conDataBase = new MySqlConnection(constring);
    MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
    MySqlDataReader myReader;

    try
    {
        conDataBase.Open();
        myReader = cmdDataBase.ExecuteReader();

        while (myReader.Read())
        {
            string namethestore = myReader.GetString("namethestore");
            string checkername = myReader.GetString("checkername");
            this.textBox65.Text = namethestore;
            this.textBox66.Text = checkername;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

【问题讨论】:

标签: c# mysql box


【解决方案1】:

当您的一个或多个字段包含 NULL (DBNull.Value) 时,您不能对它们使用 GetString
您需要使用 IsDBNull 方法检查它们是否为空,然后选择要放入文本框中的值。通常是一个空字符串

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string constring = "datasource=localhost;port=3306;username=root;password=root";
    string Query = "SELECT * from database.check WHERE patientname IS NOT NULL";
    using(MySqlConnection conDataBase = new MySqlConnection(constring))
    using(MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase))
    {
        try
        {
            conDataBase.Open();
            using(MySqlDataReader myReader = cmdDataBase.ExecuteReader())
            {
                int namePos = myReader.GetOrdinal("namethestore");
                int checkerPos = myReader.GetOrdinal("checkername");
                while (myReader.Read())
                {
                    string namethestore = myReader.IsDBNull(namePos) 
                                          ? string.Empty 
                                          : myReader.GetString("namethestore");
                    string checkername = myReader.IsDBNull(checkerPos) 
                                          ? string.Empty
                                          : myReader.GetString("checkername");
                    this.textBox65.Text = namethestore;
                    this.textBox66.Text = checkername;
                }
           }
      }
}

我还建议在一次性物品周围使用using statement。这将确保在您不再需要它们时正确关闭和处理它们,即使出现异常.....

【讨论】:

  • 我试过但我得到一个错误:'MySql.Data.MySqlClient.MySqlDataReader'不包含'IsBNull'的定义,并且没有扩展方法'IsBNull'接受'MySql.'类型的第一个参数。可以找到 Data.MySqlClient.MySqlDataReader'(您是否缺少 using 指令或程序集引用?)
  • 这是一个错字。方法名称是 IsDBNull。
猜你喜欢
  • 1970-01-01
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多