📅  最后修改于: 2023-12-03 15:05:58.051000             🧑  作者: Mango
在WinForms应用程序中,组合框(ComboBox)是一种常见的控件,允许用户从一系列选项中选择一个,或在下拉列表中输入并选择一个。在本文中,我们将介绍如何从WinForms组合框中获取选定文本。
private System.Windows.Forms.ComboBox comboBox1;
comboBox1.Items.AddRange(new object[] {"Option 1", "Option 2"});
private void button1_Click(object sender, EventArgs e)
{
string selectedText = comboBox1.SelectedItem.ToString();
MessageBox.Show("Selected item: " + selectedText);
}
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button button1;
public Form1()
{
InitializeComponent();
// 添加选项
comboBox1.Items.AddRange(new object[] { "Option 1", "Option 2" });
// 添加按钮并绑定点击事件
button1 = new System.Windows.Forms.Button();
button1.Location = new System.Drawing.Point(12, 50);
button1.Size = new System.Drawing.Size(150, 30);
button1.Text = "Get selected text";
button1.Click += new EventHandler(button1_Click);
this.Controls.Add(button1);
}
private void button1_Click(object sender, EventArgs e)
{
string selectedText = comboBox1.SelectedItem.ToString();
MessageBox.Show("Selected item: " + selectedText);
}
使用以上方法,我们可以轻松地从WinForms组合框中获取选定文本。在实际应用中,我们也可以使用SelectedValueChanged或SelectedIndexChanged事件来获取选定文本,具体的实现方式可以根据需要来选择。