2015-11-18 25 views
0

我正在使用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

請嘗試使代碼更短,只顯示有趣的部分。 – Jannik

+0

將comboBox設置爲類成員。目前它只駐留在Form1構造函數內,這就是爲什麼你會遇到錯誤。 – Harsh

回答

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

目前Combobox似乎是一個局部變量。嘗試將其設爲全局字段變量,並且您應該可以訪問它。