I have the following code in my codebehind Page_Load function that sets the default selected value of a dropdownlist in detailsview based on the name of a record returned from a sql data query.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Title = "Editing record"
'Perform dropdown list population operations
Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
If Page.IsPostBack = False Then
Dim ticket_ID As String = getDataKey(DetailsView1)
'Fetch Category ID
Dim sqlText As String = "SELECT TS_REQCATEGORY FROM USR_ITFAC WHERE (TS_ID = " + ticket_ID + ") "
Dim reqDataReader As SqlDataReader = GetDataReader(sqlText)
reqDataReader.Read()
Dim category_ID As String = reqDataReader(0)
'Fetch Category name and set as selected value in dropdown list
sqlText = "SELECT TS_NAME FROM TS_SELECTIONS WHERE (TS_ID = " + category_ID + ") "
reqDataReader = GetDataReader(sqlText)
reqDataReader.Read()
category_Name = reqDataReader(0)
'myDDL.DataBind()
myDDL.SelectedValue = category_Name
End If
End Sub
My problem is that when the page loads for the first time, even though I set the selected value for the dropdownlist it will not display and instead simply displays the default first name in my dropdownlist. I tried Binding my dropdownlist before and after I set the selectedvalue, it is commented out in the sample code above, but that didn't seem to do anything.
UPDATE: I'm setting the data source in the webform as follows:
Dropdownlist:
<asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
ID="reqCategoryDropDown" runat="server" AppendDataBoundItems="true" AutoPostBack="true">
</asp:DropDownList>
Connects to data source a few lines down:
<asp:SqlDataSource ID="ReqCategoryData" runat="server" ConnectionString="<%$ ConnectionStrings:TTPRODReportsQuery %>"
SelectCommand="SELECT TS_NAME AS ReqCategory FROM dbo.TS_SELECTIONS WHERE (TS_FLDID = 5299 AND TS_STATUS = 0) ORDER BY TS_NAME">
</asp:SqlDataSource>
UPDATE_2: Ok, so I implemented he SQLDataSource programmatically in the code-behind under the Page_Init function as follows:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
DetailsView1.DefaultMode = DetailsViewMode.Edit
''Setup DropDownList SqlDataSource
ddlDataSource.ID = "ReqCategoryData"
Page.Controls.Add(ddlDataSource)
ddlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("TTPRODReportsQuery").ConnectionString
ddlDataSource.SelectCommand = "SELECT TS_NAME AS ReqCategory FROM dbo.TS_SELECTIONS WHERE (TS_FLDID = 5299 AND TS_STATUS = 0) ORDER BY TS_NAME"
Dim args As New DataSourceSelectArguments
ddlDataSource.Select(args)
ddlDataSource.DataBind()
End Sub
After which I set attempt to set the selected value of the dropdownlist as above. The page is still not setting the selected value.