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:
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;
for (int i = 0; i < listBoxAssociations.Items.Count; i++)
{
listBoxAssociations.SetSelected(i, true);
}
listBoxAssociations.Visible = true;
}
catch (Exception ex)
{
throw;
}
}
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 dramaticallyfor (int i = 0; i < listBoxAssociations.Items.Count; i++)
{
listBoxAssociations.SetSelected(i, true);
}
listBoxAssociations.Visible = true;
}
catch (Exception ex)
{
throw;
}
}
No comments:
Post a Comment