首页 > 解决方案 > 如何从 2 个不同的组合框中获取选定的值以显示在 1 个文本框或标签内

问题描述

您好,我需要在文本框或标签内显示来自 2 个不同组合框中的选定值。我试过这段代码

int i = (int)comboBox1.SelectItem - (int)comboBox2.SelectedItem;
i += int;
{
  textBox1.Text = i.ToString
}

除了我不知道将代码放在哪里之外,该代码根本没有做任何事情。我在其中一个组合框中尝试了不同的代码,SelectedIndexChanged但它只适用于特定的代码,comboBox不适用于两者。

for (int i = 0; i < comboBox1.Items.Count; i++)
{
  textBox1.Text = comboBox1.Text;

}

我真的很感激我能得到的任何帮助。谢谢你们。

标签: c#visual-studiowinforms

解决方案


一个解决方案是在表单中有一个按钮和两个组合框和一个标签。当您按下按钮时,会添加从组合框中选择的文本,然后标签中的文本会更改。这是表格 在此处输入图像描述

private void button1_Click(object sender, EventArgs e)
    {
        //make sure that an item is selected
        if(comboBox1.SelectedItem != null &&
            comboBox2.SelectedItem != null)
        {
            //treat these like integers
            //label1.Text = Convert.ToString((Int32.Parse(comboBox1.SelectedItem.ToString()) + (Int32.Parse(comboBox2.SelectedItem.ToString()))));

            //treat them like strings
            label1.Text = comboBox1.SelectedItem.ToString() + comboBox2.SelectedItem.ToString();
        }


    }

为两个组合框选择一个项目后,您可以单击按钮,结果将像这样相互添加 在此处输入图像描述


推荐阅读