Data binding is all about declarative code, right? So I specify what I want with attributes, and the framework takes care of the rest. Unless I’m mistaken and data binding relates to S&M, right?
So, why does the DropDownList control only provide binding fields for its data source, i.e. its list source, and not for its actual data field. i.e. how the heck to I bind the selected value my name DropDownList to the Name field in my Person record? Is this a gross oversight on Microsoft’s part, or on mine?
What is the point of two way data binding if I still have to manually set and read the selected value?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You might want to do something like the code below.
You can not set the “SelectedValue” declaratively, but by saying
“SelectedValue=<%# [code here] %> you are effectively causing the value to be set when the control is data bound.
<asp:DropDownList
ID="DropDownInfoSource"
runat="server"
DataSourceID="_employeeDataSource"
DataTextField="EmployeeName"
DataValueField="EmployeeID"
SelectedValue='<%# Bind("EmployeeID") %>'
/>
Method 2
I don’t know if it will really help you, but did you tried to setup the “SelectedValue” on Code behind?
Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DropDownInfoSource.SelectedValue = "1" ' your value, here
End Sub
Method 3
There is a field where you define the datasource, the datatextfield (what shows up in the list) and the datavaluefield.
Example (I have a datatable with a column “EmployeeID” and a column “EmployeeName”):
dropdownlist1.datasource = DT dropdownlist1.datatextfield = "EmployeeName" dropdownlist1.datavaluefield = "EmployeeID" dropdownlist1.databind()
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0