Hi.
I'm having kind of a weird problem which I hope someone can help me with.
I have a form on which I have a ComboBox created at design-time.
When I run the application I dynamically create x more ComboBoxes
beneth the one created at design-time.
At run-time I set the DataSource, DataMember and ValueMember for all the ComboBoxes,
both the one created at design-time the the ones created at run-time.
After this is done I set the SelectedValue property to a value retrived
from another sql-query.
Now my problem occures. Setting the SelectedValue property works for the
control created at design-time but not for the controls created at run-time.
When I debug the code that sets the DataSources I see that the ComboBox,
created at design-time, has items in the items-collection so therefore I
can set the SelectedValue accordingly.
But the controls created at run-time doesn't have any items in the the collection.
However, if I continue to run the application and look at the run-time-created
comboboxes on the form, all the correct items is in the list.
But I can't set a selected item in code directly after setting the datasource?!?!
Does dynamically created controls need some refreshing/updating before the data is
available in the list?
Here is an excerpt from the code creating the controls and setting the properties.
cbLine1 is the ComboBox created at design-time.Code:ComboBox cbNew = new ComboBox(); cbNew.Name = "cbLine" + (i+1); cbNew.Size = cbLine1.Size; cbNew.Location = new Point(cbLine1.Location.X, cbLine1.Location.Y + 26*i); cbNew.Enabled = false; cbNew.DropDownStyle = ComboBoxStyle.DropDownList; cbNew.DataSource = DBLayer.GetTeams(lineName).Tables[0]; cbNew.DisplayMember = "teamdesc"; cbNew.ValueMember = "id"; Console.WriteLine("ComboBox {0}, itemcount={1}", cbNew.Name, cbNew.Items.Count); // The output displays itemcount = 0 for run-time created controls // and >0 for controls created at design-time gbLines.Controls.Add(cbNew);
Here is the code for setting the SelectedValue property.
What am I missing?Code:private void InitItemTeamStationData() { OleDbDataReader reader = DBLayer.GetITSData(itemID); if(reader == null) return; while (reader.Read()) { for (int i = 1; i <= numberOfLines; i++) { CheckBox chkbox = (CheckBox)gbLines.Controls["chkLine" + i]; if (chkbox != null) { int tagValue = 0; if (Int32.TryParse(chkbox.Tag.ToString(), out tagValue) == true) { if (tagValue == reader.GetInt32(reader.GetOrdinal("line"))) { chkbox.Checked = true; ComboBox team = (ComboBox)gbLines.Controls["cbLine" + i]; // The following works for design-time created controls, but not run-time team.SelectedValue = reader.GetInt32(reader.GetOrdinal("team")); ComboBox station = (ComboBox)gbLines.Controls["cbStation" + i]; // The following works for design-time created controls, but not run-time station.SelectedValue = reader.GetInt32(reader.GetOrdinal("station")); break; } } } } } }
Hope someone can help me with this.
Best regards,
Michael



Reply With Quote

Bookmarks