Clearing a Combo Box while Preserving the Selected Index
I currently have a combo box filling with data from an Access Database. This data is stored in an ArrayList which happens to be repopulated after the SelectedIndex is changed in the combo box. My remedy to removing items that are not part of the index is clearing all of the items from the combo box list but the problem is, when the list is cleared, so is the current item selected. My goal is to clear the list but preserve the selected data each time i change the item in the list so that you can see the last name selected. Any help is appreciated.
Here is some code to hopefully give you some idea of what I want to do.
//Portion that fills combo box.
employeeInformation.Clear();
employeeNamecomboBox.Items.Clear()
//label1.Text = employeeInformation.Count.ToString();
foreach (DataRow dtRow in dTable.Rows)
{
employeeNamecomboBox.Items.Add(dtRow["FirstOfNAME"].ToString() + " "
+ dtRow["SOCIAL_SECURITY_NUMBER"].ToString());
employeeInformation.Add((string)dtRow["SOCIAL_SECURITY_NUMBER"].ToString());
employeeInformation.TrimToSize();
}
//Queries database for selected info, clears image list.
private void employeeNamecomboBox_SelectedIndexChanged(object sender, EventArgs e)
{
imagelistBox.Items.Clear();
ConnectToAccess(employeeInformation[employeeNamecomboBox.SelectedIndex].ToString());
}
if more code is needed to make my situation more clear I will gladly post it.
Thanks again
Anwar BuchooPosted Feb 22, 2006, 1:34 AM
I find that you loop through each record within your datasource to populate the drop down list.
Think, instead, of making your DB query return you the combination of these 2 fields (FirstOfNAME + SOCIAL_SECURITY_NUMBER), for display and use the properties:
(1) employeeNamecomboBox.DataTextField = // the combination of the 2 fields that you returned
(2) employeeNamecomboBox.DataValueField = // for a value u want to store
Then, set the employeeNamecomboBox.DataSource = // to your DataView or DataTable ...
and call the method employeeNamecomboBox.DataBind(); // to bind the combo.
Remember, before binding the combo box, save the employeeNamecomboBox.SelectedIndex into a variable and use this method after the DataBind() method is called:
employeeNamecomboBox.Items.FindByValue(yourVal).Selected = true or
employeeNamecomboBox.Items.FindByText(yourtext).Selected = true
Here you are.
Hope it's not too a cram.
Rgds.