2

I am trying to add items to listbox from another class.

I create a form, form name called FilterControl, it has a listbox control(listBoxColumnHeaders)

I create separate class called FilterColumnHeader, There I created one method()addColumnHeader()

Now I am trying to items to listbox of FilterControl form from this FilterColumnHeader class

Here is my code:

public void addColumnHeader(string name)
    {
        try
        {
            string cs = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;

            string query = @"SELECT 
                            AsHeading
                        FROM
                            RSHeading WITH(NOLOCK);
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = query;
                cmd.Connection = con;

                con.Open();
                SqlDataReader rd = cmd.ExecuteReader();

                FilterControl fc = new FilterControl();
                while (rd.Read())
                {
                    fc.listBoxColumnHeaders.Items.Add(rd["AsHeading"].ToString());
                    MessageBox.Show(rd["AsHeading"].ToString()); //record is showing on message box
                    
                }
                
            }
        }
        catch(Exception ee)
        {
            MessageBox.Show(ee.ToString());
        }
        
    }

Note

If I try directly from the same form(FilterControl). It is working fine, Also the database is retrieved record successfully.

I set the modifiers of listbox control to Public

Community
  • 1
  • 1
Liam neesan
  • 2,282
  • 6
  • 33
  • 72
  • 1
    `FilterControl fc = new FilterControl();` You are creating a new instance of the form, than the form which you see. – Reza Aghaei Feb 03 '18 at 21:47
  • @RezaAghaei then how can I access that `FilterControl` properties in another class? Sorry I am new to winforms app. – Liam neesan Feb 03 '18 at 21:49
  • [Interaction between forms — How to change a control of a form from another form?](https://stackoverflow.com/q/38768737/3110834) – Reza Aghaei Feb 03 '18 at 21:51

1 Answers1

1

Try this accessing your form inside the class:

var fc= Application.OpenForms.OfType<FilterControl>().SingleOrDefault();
while (rd.Read())
            {
                fc.listBoxColumnHeaders.Items.Add(rd["AsHeading"].ToString());
                MessageBox.Show(rd["AsHeading"].ToString()); 
            }
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57