0

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);
                }
            }
        }
    }
  • 1
    What is causing the SelectedValue property to be null is unclear, but surely, blindly taking an object reference and applying ToString is a recipe to get this error. Instead use the [NullConditionalOperator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-) – Steve Jun 14 '20 at 08:35
  • i'm using stored procedures to insert and update data, I have not yet learned how to get data from stored procedure (accessing data from the stored procedure – Johannes Motsepe Jun 14 '20 at 08:35
  • @viveknuna OP uses `using` for the connection already and I don't see how a stored procedure could help here. – Bill Tür stands with Ukraine Jun 14 '20 at 08:36
  • please note that the string below the query string is supposed to read: "string clientID = CmbCartClientID.SelectedValue.ToString();" without the "!= null" – Johannes Motsepe Jun 14 '20 at 08:37
  • Thanks Steve, the solution you gave above the question helped me. – Johannes Motsepe Jun 14 '20 at 09:00

0 Answers0