Thursday, March 22, 2012

Setting the default value for a data bound drop down list item.

Can someone please tell me how to set an asp:DropDownList default/pre-selected value when it's bound to a data source. My html and vb code looks like this


<asp:DropDownList id="lstStatus" runat="server" Width="403px" DataTextField="statusName" DataValueField="statusID" class='textbox'></asp:DropDownList
Function GetStatuses() As System.Data.IDataReader
Dim connectionString As String = connectionStringToAssignSQLServer
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT tblStatus.[statusID], tblStatus.[statusName] FROM tblStatus"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

dbConnection.Open
Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

Return dataReader
End Function

Sub Page_Load(Sender as Object, e as EventArgs)
lstStatus.DataSource = GetStatuses()
lstStatus.DataBind()
End Sub

the drop down list has five values selected from the database. I want the current value eg (raised) to be the selected value instead of the order it comes from the database. In case you were wondering, It is possible to pass the current value (ID) from the previous page.

Thanks a lot.Once the ddl is populated, you make the query to the database for the item you want selected --

Then:
DropDownList.Items.FindByText("TextYouWantSelected").Selected = true
Thanks a lot! it worked straight away!

0 comments:

Post a Comment