Click here to Skip to main content
11,929,924 members (55,799 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# C#4.0
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()

        private void button1_Click(object sender, System.EventArgs e)
            string selectedItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();

Form Designer Content
private void InitializeComponent()

this.button1 = new System.Windows.Forms.Button();
// 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.Name = "Form1";
this.Text = "Form1";

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;


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;

Posted 21-Jan-13 22:07pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Object combobox1 has a scope limited to your InitializeComboBox. And that's why you cannot use it in the handler.

Also, please call InitializeComboBox method after InitializeComponent method.
Sumit Lotankar 22-Jan-13 3:36am
How to change its scope so as it is available to the handler;
d@nish 22-Jan-13 5:35am
You can make it a class level variable.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web04 | 2.8.151126.1 | Last Updated 22 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100