On load the combobox is loaded with a column from the database, I created a selectedIndexChanged so that when the value changes in the combobox, i would select data from the database and populate a richTextbox. This works fine, but when I try close the form it throws an Exception unhandled error stating that "Object reference not set to an instance of an object" - "System.Windows.Forms.ListControl.SelectedValue.get returned null". Is there anything I'm doing wrong? Blow is the code:
private void CmbCartClientID_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "[string removed but valid connection string]";
string query = "SELECT * FROM tblClientInfo WHERE client_ID = @clientID";
string clientID = CmbCartClientID.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@clientID", SqlDbType.VarChar).Value = clientID;
try
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
RtxtCartClientInfo.Text = sdr["c_name"].ToString() + " " + sdr["c_surname"].ToString();
clientID = "";
}
con.Close();
}
catch (SqlException ex)
{
_ = MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}