A Combobox Question (Windows Forms)

  • Thread starter Ing. Rajesh Kumar
  • Start date
I

Ing. Rajesh Kumar

Hi everybody
I am a web developer now trying to do something in WinForms using VB.NET and
have a small problem with ComboBox. I just wanted to ask what is the
equivalent to the following web code :

Dim MyString as String
Do While DR.Read()
Select Case DR("Column_1")
Case "X" : MyString = "XXXX"
Case Else : MyString = DR("Column_1")
End Select
DropDownList1.Items.Add(New ListItem(MyString, DR("Column_2")))
Loop

'Could also be : For i = 0 To 5 and then DropDownList1.Items.Add(New
ListItem("Item " & i, i))

In WinForms i can add only one item as :
DropDownList1.Items.Add("XXXX")
but i need to add KEY and VALUE.
I read a lot in the MSDN and found a way to do this using dataset,
DisplayMember, ValueMember and a helper class but not an easy way.

Thanks in advace
Raja
 
S

SStory

Raja, the basic idea in winforms is to

create a class for your list items.
put whatever you want into it.
Override the ToString method and that is what the list will display but the
selected item will be an instance of the class you defined and contain
whatever you wanted.

HTH,

Shane
 
C

Cor Ligthert

Raja,

You can do it in almost the same way you wrote.

DropDownList.items.add(mystring)
should be enough in that case
and than set the combobox style to dropdownlist

with a dataset it would be because you have already your connection and
selectstring
\\\
myLoadedSwitch = false
dim ds as new dataset
dim da as new xxxDataadapter(sqlstring,conn)
da.fill(ds)
ds.tables(0).columns.add(see links)
DropDownList1.datasource = ds.tables()
DropDownList1.displaymember = "MynewColumn"
DropDownList1.valuemember = "Myvaluecolumn"
///

http://msdn.microsoft.com/library/d.../frlrfsystemdatadatacolumnclassctortopic4.asp

http://msdn.microsoft.com/library/d...fSystemDataDataColumnClassExpressionTopic.asp

The advantage from the last is that you have extra a value column and pass a
bug with the selection change commitet event.

When you use it you have to set in the the indexchange event (there are
alternatives too)
If myLoadedSwitch = true
' This because some anoying load efects of the combobox.

As last use as control name someting as cmb not dropdownlist, these are of
the few controls where the webcontrols and the winforms have a well distinct
in there name.

(All is typed in this message and not checked on typos)

I hope this helps?

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top