简体   繁体   English

如何从组合框C#获取值?

[英]How to get a value from a combobox c#?

I'm a little new to C#, so bear with me on this one... 我是C#的新手,所以请耐心等待...

Okay, so you right click a comboBox, select edit items, and you can add strings to the comboBox. 好的,因此您右键单击comboBox,选择编辑项,然后可以将字符串添加到comboBox。 My question is, how can I set a value to those strings? 我的问题是,如何为这些字符串设置值? I want to use an 'if' statement to state whether a certain string is currently selected. 我想使用“ if”语句来说明当前是否选择了某个字符串。

So I have 5 comboBoxes. 所以我有5个comboBoxes。 When a checkbox is checked, all of them will say 'Full'. 选中复选框后,所有的人都会说“满”。 If one of those values is changed to something else, then I want a different checkbox to be checked. 如果这些值之一更改为其他值,那么我希望选中另一个复选框。 But since the strings in the comboBoxes have no values, I can't figure out how to use them. 但是由于comboBoxes中的字符串没有值,所以我不知道如何使用它们。

To reiterate, how can I set values to the strings in the comboBoxes so I can use them in 'if' statements. 重申一下,如何为comboBoxes中的字符串设置值,以便可以在“ if”语句中使用它们。

Edit: This is a Windows Form. 编辑:这是Windows窗体。

Well, the most simple way: 好吧,最简单的方法:

Combobox.Items.Add("New string");

The more complex way is to create an array or list of strings and add them all at once as a Datasource: 更为复杂的方法是创建一个数组或字符串列表,并将它们全部一次添加为数据源:

var listOfStrings = new List<string>();
Combobox.Datasource = listOfStrings;

No matter what way you choose, you will edit the collection of ComboBox Items. 无论选择哪种方式,都将编辑ComboBox项目的集合。

PS That's for Winforms. PS那是Winforms的。

check text the Text property. 检查文本的Text属性。

Assuming your ComboBox is in cmb[5], and your check box is chk: 假设您的ComboBox位于cmb [5]中,并且您的复选框为chk:

private ComboBox[] cmb;

private void init()
{
    cmb = new ComboBox[5];
    for (int i = 0; i < 5; i++)
    {
        ComboBox c = new ComboBox();
        Controls.Add(c);
        // TODO: Populate c with the relevant data
        c.TextChanged += new EventHandler(c_TextChanged);
    }
    chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
}

void chk_CheckedChanged(object sender, EventArgs e)
{
    foreach (ComboBox c in cmb)
        c.Text = "Full";
}

void c_TextChanged(object sender, EventArgs e)
{
    foreach (ComboBox c in cmb)
    {
        if (c.Text != "Full") return;
    }
    chk.Checked = false;
}

Alternatively, init could be: 另外,init可以是:

private void init()
{
    cmb = new ComboBox[5];
    cmb[0] = comboBox1;
    cmb[1] = comboBox2;
    cmb[2] = comboBox3;
    cmb[3] = comboBox4;
    cmb[4] = comboBox5;
    foreach (ComboBox c in cmb)
        c.TextChanged += new EventHandler(c_TextChanged);
    chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM