Friday, May 3, 2013

How to add items to a Listbox control on a Windows Form

When adding to a listbox on a windows form, the following error sometimes occurs:

Items collection cannot be modified when the DataSource property is set.

This is how I worked around that issue:


        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                List<string> items = new List<string>();
                const string connectionString = "Data Source=DBTest; Initial Catalog=master; Trusted_Connection=yes;";
                const string sql = "SELECT name FROM  master.dbo.sysdatabases WHERE (name LIKE 'Agware%') ORDER BY name";
                using (DataTable results = GetDataTable(connectionString, sql))
                {
                    listBoxAssociations.DataSource = results;
                    foreach (DataRow r in results.Rows)
                    {
                        items.Add((string)r[0]);
                    }
                }
                listBoxAssociations.DataSource = items;


            //Now select all items in list box
            listBoxAssociations.Visible = false; //hiding the listbox increases the performance dramatically
            for (int i = 0; i < listBoxAssociations.Items.Count; i++)
            {
                listBoxAssociations.SetSelected(i, true);
            }
            listBoxAssociations.Visible = true;  



            }

            catch (Exception ex)
            {
                throw;
            }
        }
 

No comments:

Post a Comment