Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

database - Bound combobox items refers to different field items

I got a bounded combobox to a group name in vb.net. i can view in the drop down items of the combobox the set of GROUP NAMES. but when i do an insert or update query, i need to make the selected group name refers to the GROUP NUMBER. I don't want to store letters in the database, instead i prefer numbers. how can i do that?!

Here is my code so far :

cmd1.Parameters.AddWithValue("@group", DirectCast(Additemcombobox.SelectedItem, 
                                  DataRowView).Item("GroupName"))

Storing the group name in database is currently working well.

My question might not be well explained. Please ask me in case... any help would be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can show one element to the user such as the name, but use a different one for the code to identify the item using DisplayMember and ValueMember

Dim SQL = "SELECT Id, Name FROM GroupCode ORDER BY Name"
... 
GrpDT = New DataTable
GrpDT.Load(cmd.ExecuteReader)

cboGroup.DataSource = GrpDT
cboGroup.DisplayMember = "Name"
cboGroup.ValueMember = "Id"

The user will only see the names, while the code can use ValueMember:

Private Sub cboGroup_SelectedValueChanged(...etc
    Console.WriteLine(cboGroup.SelectedValue)
End Sub

It prints the Group ID not the name. Depending on the ORDER BY clause in the SQL and the ID, the SelectedIndex may or may not match, so respond to SelectedValueChanged event. If you use SelectedValue instead of SelectedItem you wont have to thrash about with a DataRowView item.

Note that SelectedValue is Object so you will have to cast to integer or whatever for use elsewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...