0

我有 2 个名为cBTeam1( cBTeam2winForm & 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组合框中

4

2 回答 2

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();
        }
    }
于 2013-07-25T08:09:49.040 回答
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();
    }
于 2013-07-25T08:16:35.780 回答