Click here to Skip to main content
15,892,768 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have a table in sqlServer like this:

ID Title Description
-----------------------------------
1 Director
3 Actor
5 Producer

And in my project there is 2 Form:
1. Activity
2. ActivityDialog

When I Click on Edit_Click() the ActivityDialog will be shown.

There is a DataBound comboBox in ActivityDialog Form which its DisplayMember is "Title" and ValueMember is "ID".
At ActivityDialog_Load() I want to set selectedIndex for comboBox to show the current record's ActivityType.

I have tried these but both of them returns -1:

C#
comboBox.SelectedIndex = comboBox.Items.IndexOf(1);

And
C#
comboBox.SelectedIndex = comboBox.Items.IndexOf("Director");
Posted
Updated 16-Aug-12 12:00pm
v2
Comments
Sergey Alexandrovich Kryukov 16-Aug-12 19:39pm    
To be clear, you need to show the code sample where you add elements to the control.
--SA

1 solution

Try this:
comboBox.SelectedIndex = 1;

and the combobox is usually boiunded to a collection, so get the index in the collection in code insted.
 
Share this answer
 
v2
Comments
[no name] 16-Aug-12 17:52pm    
You didn't understand.
The form is an Edit Dialog so I should Set the comboBox value dynamically.
Kenneth Haugland 16-Aug-12 17:55pm    
Now I really dont understand you rproblem. If you wan tto select a specific index you should get it by the datatable or list you are populationg the items from. If you have recently added the item and want the last you added, simply use comboBox.Items.Count-1.
[no name] 16-Aug-12 18:01pm    
See new Version of question.
Kenneth Haugland 16-Aug-12 18:04pm    
It was just more confusing, if you whish to get the element you simply call the selectedindex and do something like MyList(comboBox.SelectedIndex) to get the corresponding row...
[no name] 16-Aug-12 18:14pm    
When comboBox is not DataBound IndexOf() work perfectly.
for example I'd tried this before:

int year = 2012;
for (int i = 0; i < 20; i++)
{
this.comboBox.Items.Add(year);
year--;
}
then somewhere else:
comboBox.SelectedIndex = comboBox.Items.IndexOf("2010");
And the SelectedIndex value got 2;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900