开发者

How to get a value from a combobox c#?

I'm a little new to C#, so bear with me on this one...

Okay, so you right click a comboBox, select edit items, and you can add strings to the 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.

So I have 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 开发者_StackOverflowuse them.

To reiterate, how can I set values to the strings in the comboBoxes so I can use them in 'if' statements.

Edit: This is a Windows Form.


check text the Text property.

Assuming your ComboBox is in cmb[5], and your check box is 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:

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


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.

PS That's for Winforms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜