我有我的代碼隱藏Page_Load函數中的下面的代碼,根據從sql數據查詢返回的記錄的名稱在detailsview中設置dropdownlist的默認選定值。ASP.Net dropdownlist內detailsview不在代碼隱藏設置
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
我的問題是,當頁面加載的第一次,即使我的下拉列表設置選擇的值不會顯示出來,而是隻顯示在下拉列表我的默認名字。我嘗試在設置selectedvalue之前和之後綁定我的下拉列表,它在上面的示例代碼中註釋掉了,但似乎沒有做任何事情。
更新: 我設置數據源中的Web窗體如下:
DROPDOWNLIST:
<asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
ID="reqCategoryDropDown" runat="server" AppendDataBoundItems="true" AutoPostBack="true">
</asp:DropDownList>
連接到數據源的幾行字下來:
<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 : 好的,所以我在Page_Init函數的代碼隱藏中以編程方式實現了他的SQLDataSource,如下所示:
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
之後我設置嘗試設置下拉列表的選定值如上。該頁面仍未設置所選值。
我沒有看到這裏列出的數據源和數據綁定評論目前註釋掉(與單引號有)所以這看起來是發生了什麼事。 – 2010-07-21 15:45:10
我在上面添加了一些細節,我實際上是在Web表單本身設置數據源。並且是p.cambell,我確定第0個索引包含我想要設置DataValueField的值。驗證我包含調試時的值。 – kingrichard2005 2010-07-21 15:52:31