Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C# combobox WinForm
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 12:45pm
Edited 16-Aug-12 13:00pm
Sergey Alexandrovich Kryukov at 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 at 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 at 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 at 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 at 16-Aug-12 19:40pm
Next time please think at your question to make sure you provide sufficient information.
Sergey Alexandrovich Kryukov at 16-Aug-12 19:41pm
My 5. It's hard to keep patience...
Kenneth Haugland at 16-Aug-12 20:11pm
Thank you, Sergey :)
ridoy at 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
0 Peter Leow 315
1 Mika Wendelius 275
2 CHill60 190
3 TheRealSteveJudge 184
4 Abhinav S 170
0 Sergey Alexandrovich Kryukov 8,613
1 OriginalGriff 6,546
2 Peter Leow 3,897
3 Zoltán Zörgő 3,456
4 Richard MacCutchan 2,472

Advertise | Privacy | Mobile
Web04 | 2.8.150123.1 | Last Updated 16 Aug 2012
Copyright © CodeProject, 1999-2015
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