gpt4 book ai didi

c# - 数据为空。不能对空值调用此方法或属性。(使用组合框)

转载 作者:行者123 更新时间:2023-11-29 18:37:15 25 4
gpt4 key购买 nike

您好,我的表中有空值,我将使用它来填充组合框。我不知道该怎么做。当我运行以下代码时,出现错误:

Data is Null. This method or property cannot be called on null values.

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

最佳答案

当您的一个或多个字段包含 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周围的一次性元素。这将确保当您不再需要它们时,以及在出现异常的情况下正确关闭和处置......

关于c# - 数据为空。不能对空值调用此方法或属性。(使用组合框),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45185875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com