正在从组合框所选项目中检索值

本文关键字:项目 检索 选项 组合 | 更新日期: 2023-09-27 18:22:23

我使用的是Windows应用程序。我将一些数据作为直接值放在组合框中。我将var类型定义为组合框。我把这些组合框放在表单加载上。现在我想在button2_click事件上检索所选项目的值,我尝试了下面的代码来检索它,但它给我的错误是当前上下文中不存在名称组合框。有人能建议我怎么修吗?

namespace WinDataStore
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            var daysOfWeek =
                new[] { "RED", "GREEN", "BLUE"
                         };
            // Initialize combo box
             var comboBox = new ComboBox
            {
                DataSource = daysOfWeek,
                Location = new System.Drawing.Point(180, 140),
                Name = "comboBox",
                Size = new System.Drawing.Size(166, 21),
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            // Add the combo box to the form.
            this.Controls.Add(comboBox);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // Create a new instance of FolderBrowserDialog.
            FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
            // A new folder button will display in FolderBrowserDialog.
            folderBrowserDlg.ShowNewFolderButton = true;
            //Show FolderBrowserDialog
            DialogResult dlgResult = folderBrowserDlg.ShowDialog();
            if (dlgResult.Equals(DialogResult.OK))
            {
                //Show selected folder path in textbox1.
                textBox1.Text = folderBrowserDlg.SelectedPath;
                //Browsing start from root folder.
               Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (!textBox1.Text.Equals(String.Empty))
            {
                if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
                {
                    foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
                    {
                        //Add file in ListBox.
                        listBox1.Items.Add(file);
                    }
                }
                else
                {
                  //  listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
                }
            }
            string s = (string)comboBox.SelectedItem;
            listBox1.Items.Add(s);
        }
    }
}

正在从组合框所选项目中检索值

comboBoxForm1.ctor中的局部变量。您不能从其他方法访问它

选项:

1) 通过名称访问控制

private void button2_Click(object sender, EventArgs e)
{
    var comboBox = this.Controls["comboBox"] as ComboBox;
    ...
}

2) 如果控件是在设计器中创建的,则将其作为窗体的私有成员

ComboBox comboBox;
public Form1()
{
    InitializeComponent();
    // Initialize combo box
    comboBox = new ComboBox() {...};
    ...
}

当前组合框似乎是一个局部变量。尝试使其成为全局字段变量,您应该能够访问它。