0

I am trying to populate a listbox with the following code but I get an error saying ListItem could not be found. Also rathen than creating a new listbox here I want to populate one on my windows forms gui called listbox1 but it says it does not exist in the current context if I change the first line to ListBox lb = listbox1();

ListBox lb = new ListBox(); 
string connectionString = "your connection string here"; 
using (SqlConnection con = new SqlConnection(connectionString)) 
{ 
    con.Open(); 
    string query = "SELECT column FROM myitemstable"; 
    using (SqlCommand cmd = new SqlCommand(query, con)) 
    { 
        using (SqlDataReader reader = cmd.ExecuteReader()) 
        { 
            while (reader.Read()) { 
                lb.Items.Add(new ListItem((string)reader["column"])); 
            } 
        } 
    } 
} 
3
  • listbox1.Items.Add(new ListItem((string)reader["column"])); . no need to declare anything Commented Jun 15, 2012 at 10:31
  • What do you mean exactly what do I need to add/remove? Commented Jun 15, 2012 at 10:36
  • no worries I have sorted it thanks Commented Jun 15, 2012 at 10:40

1 Answer 1

1

when you drag and drop control to UI, Visual studio generate code for it. (Check your designer.cs file)

listbox1 is the object created by the designer, you can directly add items to it.

you can't do below

ListBox lb = listbox1();

because listbox1 is object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.