Hi I have nulls in a table that I will use to populate a combo box. I am not sure how to do this. When I run the below code I get the error:
Data is Null. This method or property cannot be called on null values.
I need help and I'm new to mysql
the code :
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);
}
}
When one or more of your fields contains a NULL (DBNull.Value) you cannot use GetString
on them.
You need to check if they are null using the IsDBNull method and choose what value you want to put in the textbox instead. Usually it is an empty string
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;
}
}
}
}
I suggest also to use the using statement around the disposable objects. This will ensure a proper closing and disposing when you don't need them anymore, also in case of exceptions.....