从组合框选定项中检索值

时间:2015-11-18 06:08:03

标签: c#

我正在使用Windows Application.I将一些数据作为直接值放在组合框中。我将var类型定义为组合框。我将这些组合框放在表单上。现在我想在button2_click上检索所选项目的值事件和我尝试下面的代码来检索它,但它给我的错误名称comboBox在当前上下文中不存在。可以任何人建议我如何解决它。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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() {...};
    ...
}