5

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

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

我需要帮助,我是 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);
    }
}
4

1 回答 1

9

当您的一个或多个字段包含 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 语句。这将确保在您不再需要它们时进行适当的关闭和处置,即使是在异常情况下......

于 2014-07-04T22:37:13.310 回答