I want to fill the data using DataReader in listbox/combobox with data showing description, but at the time of save I want to store the ID in the database. How do I do that?
After you add a DropDownList to a form, set its DataTextField to the datareader field you want to display, and the DataValueField to the field you want stored. Filling the control is a matter of executing a command and databinding to the reader:
OleDbCommand cmd = new OleDbCommand("select EmployeeID, LastName from Employees", this.cnConnection); this. cnConnection.Open(); OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cbEmployees.DataSource = reader; cbEmployees.DataBind();
Now, whenever you want to get the current value (not the text displayed), you ask for the control SelectedValue property. Alternatively, you can use the SelectedItem property which exposes Text, Value and Selected (for a list) properties about the current item.
Dig Deeper on Win Development Resources
Related Q&A from Daniel Cazzulino
Here Daniel Cazzulino explains how to load a DSL (domain specific language) domain model instance file programmatically. This requires the .NET type ... Continue Reading
Here we offer a glimpse at 12 of .NET development expert Danny Cazzulino's top ASP.NET questions and answers. Continue Reading
C# developers should NOT be modifying InitializeComponent method in the code-behind (or any of the variable definitions) by hand. Continue Reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.