Click here to Skip to main content
12,545,876 members (59,991 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# combobox
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:

comboBox.SelectedIndex = comboBox.Items.IndexOf(1);
comboBox.SelectedIndex = comboBox.Items.IndexOf("Director");
Posted 16-Aug-12 11:45am
Updated 16-Aug-12 12:00pm
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.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Try this:
comboBox.SelectedIndex = 1;

and the combobox is usually boiunded to a collection, so get the index in the collection in code insted.
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.
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...
Kenneth Haugland 16-Aug-12 18:18pm
Have you put a debug mark in the solution to check that the item actually exists, no spelling mistakes or anythong like that?
Sergey Alexandrovich Kryukov 16-Aug-12 19:40pm
Next time please think at your question to make sure you provide sufficient information.
Sergey Alexandrovich Kryukov 16-Aug-12 19:41pm
My 5. It's hard to keep patience...
Kenneth Haugland 16-Aug-12 20:11pm
Thank you, Sergey :)
ridoy 17-Aug-12 2:04am
comboBox.selectedIndex =1 is the right solution

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.161018.1 | Last Updated 16 Aug 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100