Form1 has two controls button and combo box
Button is added at design time and combo box at run time,Click event on the Button
refrencing the combo Box comes up with the Error (combo box does not exist in current context)
=============================================
Form1.cs Content
============================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace combotest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComboBox();
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
string selectedItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();
MessageBox.Show(selectedItem);
}
}
}
=======================================
Form Designer Content
=======================================
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(95, 101);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
private void InitializeComboBox()
{
//this.ComboBox1 = new System.Windows.Forms.ComboBox();
System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox();
comboBox1.Location = new System.Drawing.Point(20, 60);
comboBox1.Name = "comboBox1";
comboBox1.Size = new System.Drawing.Size(245, 25);
comboBox1.BackColor = System.Drawing.Color.Orange;
comboBox1.ForeColor = System.Drawing.Color.Black;
this.Controls.Add(comboBox1);
comboBox1.DropDownHeight = 70;
comboBox1.DropDownWidth = 350;
comboBox1.Items.Add("Mahesh Chand");
comboBox1.Items.Add("Mike Gold");
comboBox1.Items.Add("Praveen Kumar");
comboBox1.Items.Add("Raj Beniwal");
}
private Button button1;
}