Search code examples
c#sqlcombobox

C# Code to populate ComboBox with database column values is not returning unique values


My code to populate a ComboBox with unique value list of the items in an SQL database column is not functioning as required. It is simply mirroring the list of items in the column, even if there are multiple identical entries. I am new to coding, please help a solution for this in English.

void Fillcombo()
    {
        
        if (sqlconf2.State == ConnectionState.Closed)
            sqlconf2.Open();
        //after connection is open, using following "if" code to check uniqueness of Step
        string query = "Select [Animal ID] from ExpData where SystemUser = '" + textBox15.Text.Trim() + "' ;" ;
        SqlCommand cmd = new SqlCommand(query, sqlconf2);

        
        try
        {
            SqlDataReader myda = cmd.ExecuteReader();
            while (myda.Read())
            {
                string AnIDs = myda.GetString(0).ToString();
                comboBox4.Items.Add(AnIDs);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlconf2.Close();
        }
    }

Solution

  • Change your query to this

     string query = "Select Distinct [Animal ID] As AnimalId from ExpData
     where SystemUser = '" + textBox15.Text.Trim() + "' Order By [Animal ID] ;" ;
    

    And for the smart guys I recommend you to use a parameter instead of textBox15.Text