combobox Selected Text更改了事件未触发

时间:2015-07-10 17:40:08

标签: c# winforms

这是我的代码。通过DataSource添加数据后,SelectedIndexChanged事件未触发。

try
{
    comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
    comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;

    //comboBox1.Items.Clear();

    comboBox1.ResetText();

    Cn.Open();
    SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
    SqlDataReader da = Cd.ExecuteReader();
    DataTable dt = new DataTable();

    dt.Columns.Add("Mobile", typeof(string));
    dt.Load(da);
    comboBox1.DisplayMember = "Mobile";
    comboBox1.DataSource = dt;
    comboBox1.SelectedItem = "<Select>";
}
catch
{

}
finally
{
    Cn.Close();
    Clear();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Label CBSL = new Label();
    //string CBSL = this.comboBox1.SelectedItem.ToString();

    if (comboBox9.Text == "Client")
    {
        Update_Read_Client();
    }
    else if (comboBox9.Text == "Customer")
    {
        Update_Read();
    }
}
  1. 一次又一次地选择第一个值。
  2. 我曾尝试过DropDownStye = DropDownList。但是它变成了休眠状态。没有添加任何值。
  3. 解决问题的任何帮助。

1 个答案:

答案 0 :(得分:0)

我不确定你是否有“&lt; Select&gt;”保存在数据库中的项目。此外,使用DataTable时,使用SqlDataAdapter更容易填充它。在编写这样的查询时,您还应该使用参数而不是字符串concat,using关键字在您完成使用后自动关闭连接。我可能会这样写:

comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;

using (SqlConnection con = new SqlConnection(connectionString))
{
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = @"SELECT DISTINCT Mobile
                        FROM Client_Details
                        WHERE Branch = @Branch";
    cmd.Parameters.AddWithValue("@Branch", label2.Text);

    try
    {
        var dt = new DataTable();
        dt.Columns.Add("Mobile", typeof(string));

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

        DataRow row = dt.NewRow();
        row["Mobile"] = "<Select>";                    
        dt.Rows.InsertAt(row, 0);

        comboBox1.DisplayMember = "Mobile";
        comboBox1.DataSource = dt;
        comboBox1.SelectedItem = "<Select>";
    }
    catch
    {
        throw;
    }
}