嗨,我在表格中将使用空值来填充组合框。我不确定该怎么做。当我运行以下代码时,出现错误:
数据为空。不能在空值上调用此方法或属性。
我需要帮助,并且是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方法检查它们是否为空,然后选择要在文本框中输入的值。通常是一个空字符串
GetString
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语句。这样可以确保当您不再需要它们时,也可以进行适当的关闭和处理,以防万一。