我需要一点帮助。我有一个名为 Form1
的主窗体。
当我单击按钮 btn1
时,将出现一个名为 Form2
的新表单。
在 Form2
中,我有几个文本框和一个名为 cb2
的组合框。
对于文本框,我这样设置显示的文本:
//on Form1 I have this code
private void btn1_Click(object sender, EventArgs e)
{
Form2 form2= new Form2();
string a = "Text to be displayed in a textBox";
form2.txtMyTextBox = a;
form2.Owner = this;
form2.ShowDialog(this);
}
//on Form2 I set Public String
public string txtMyTextBox
{
get { return txt1.Text; }
set { txt1.Text = value; }
}
如何在 ComboBox 下拉菜单中设置所选项目?我尝试了与文本框相同的方法,但它不起作用。
//Tried for combobox
public string myCb2
{
get { return cb2.Text; }
set { cb2.SelectedValue = value; }
}
最佳答案
您可以在表单的属性中公开 ComboBox 的 SelectedIndex
属性:
public int MySelectedIndex // user a more appropriate name
{
get { return cb2.SelectedIndex; }
set { cb2.SelectedIndex = value; }
}
这只给你索引。如果需要选中项的文字,需要使用SelectedItem
:
public string MySelectedItem // user a more appropriate name
{
get { return cb2.SelectedItem.ToString(); }
}
我使用了 ToString()
方法,因为 SelectedItem
的类型是对象。根据您在 ComboBox 的 Items
属性中填充的对象,基础类型可以是任何类型。如果你把字符串放在里面,你会得到字符串,然后你可以只使用强制转换:
public string MySelectedItem // user a more appropriate name
{
get { return (string)cb2.SelectedItem; }
set { return cb2.SelectedItem = value; }
}
关于C# WinForms 在新表单中选择 ComboBox 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20742722/