从combobox2中删除combobox1中的选定项目。 (组合框与数据库绑定。)

时间:2013-07-23 23:18:43

标签: c# winforms combobox

我有两个名为cBTeam1cBTeam2(winForm& C#)的组合框,它们都绑定在同一个数据库表中。

如果某人从cBTeam1中选择了一个团队,我希望此选定的团队不会显示在cBTeam2中。

     private void bindComboBox()
    {
       if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            string queryTeam1 = "SELECT * FROM Teams ORDER BY Team_name";

            SqlCommand cmd = new SqlCommand(queryTeam1, con);
            adapter = new SqlDataAdapter(cmd);
            adapter.Fill(ds, "Teams");

            this.cBoxTeam1.SelectedIndexChanged -= new EventHandler(this.cBoxTeam1_SelectedIndexChanged);
            cBoxTeam1.DataSource = ds.Tables["Teams"];
            //if(cBoxTeam1.SelectedIndex


            cBoxTeam1.DisplayMember = "Team_name";
            cBoxTeam1.SelectedIndex = -1;
            cBoxTeam1.ValueMember = "team_id";
            this.cBoxTeam1.SelectedIndexChanged += new EventHandler(this.cBoxTeam1_SelectedIndexChanged);
   }  

这是cBoxTeam2事件处理程序cBoxTeam2_SelectedIndexChanged

的代码
    private void cBoxTeam2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cBoxTeam1.SelectedIndex == cBoxTeam2.SelectedIndex)
        {
            MessageBox.Show("You already selected " + cBoxTeam2.Text);
        }


        team2_id = Int32.Parse(cBoxTeam2.SelectedValue.ToString());
    }

例如cBoxTeam1显示3个值,即英格兰,印度,澳大利亚。 如果我选择印度,选择后印度不会显示在cBoxTeam2组合框

2 个答案:

答案 0 :(得分:0)

嘿,我为你做了样本。示例有2个组合框并绑定相同的数据源。当我选择combobox1时,首先检查列表是否存在绑定combobox 2除了匹配的项目。

 protected List<string> lst
    {
        get
        {
            List<string> lst =
                new List<string>();
            lst.Add("1");
            lst.Add("2");
            lst.Add("3");
            return lst;
        }
    }

   private void Form1_Load(object sender, EventArgs e)
    {            
        comboBox1.DataSource = lst;
        comboBox2.DataSource = lst;
    }

   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lst.Contains(comboBox1.SelectedItem.ToString()))
        {
            comboBox2.DataSource = lst.Select(q => q.ToString(CultureInfo.InvariantCulture)).Where(q => q.ToString() != comboBox1.SelectedItem).ToList();
        }
    }

答案 1 :(得分:0)

试试这个

    public void loadcBTeam1()
    {
       ....
       string queryTeam1 = "SELECT Team_name FROM Teams  where Team_name <> '" + yourComboBox2.text + "' ORDER BY Team_name";
     ......
    }

并在您的ComboBox2 TextChanged

   private void comboBox2_TextChanged(object sender, EventArgs e)
    {
        loadcBTeam1();
    }