使用数据库列值填充 ComboBox 的 C# 代码不返回唯一值

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

我使用 SQL 数据库列中项目的唯一值列表填充 ComboBox 的代码未按要求运行。它只是简单地镜像列中的项目列表,即使有多个相同的条目。我是编码新手,请用英文帮助解决这个问题。

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();
        }
    }

将您的查询更改为此

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

对于聪明的人,我建议您使用参数而不是 textBox15.Text