在初始页面加载时设置下拉列表选定值

时间:2010-07-22 18:56:50

标签: asp.net asp.net-ajax webforms

我之前发过一个类似的问题,但没有一个答案有效,我一直在寻找解决方案。我的情况,我有一个带有下拉列表的编辑窗口webform(注意:为避免混淆,我只使用Telerik扩展来装饰webform):

 <%@ Page Language="VB" CodeFile="EditFormVB.aspx.vb" Inherits="EditFormVB" %>
<%@ Register Namespace="CustomBoundField" TagPrefix="custom" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Edit Pop-up</title>
</head>
<body class="">
    <form id="form1" runat="server">
        <div>

            <script  type="text/javascript">
                function CloseAndRebind(args) {
                    GetRadWindow().BrowserWindow.refreshGrid(args);
                    GetRadWindow().close();
                }

                function GetRadWindow() {
                    var oWindow = null;
                    if (window.radWindow) oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
                    else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow; //IE (and Moz as well)

                    return oWindow;
                }

                function CancelEdit() {
                    GetRadWindow().close();
                }
            </script>

            <asp:ScriptManager ID="ScriptManager2" runat="server" />
            <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" DecoratedControls="All" />
            <br />
            <br />

            <asp:DetailsView ID="DetailsView1" DataKeyNames="ID" runat="server" AutoGenerateRows="False"
                GridLines="None" DataSourceID="detailsSqlDataSource" Height="50px" Width="125px"
                BorderWidth="0" CellPadding="0" CellSpacing="7">
            <Fields>
                <asp:BoundField DataField="TS_DESCRIPTION" HeaderText="TS_DESCRIPTION" SortExpression="TS_DESCRIPTION" />
                <asp:BoundField DataField="TS_TITLE" HeaderText="TS_TITLE" SortExpression="TS_TITLE" />
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowInsertButton="True" />
            </Fields>
            </asp:DetailsView>--%>

            <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
            <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" />
            <br />
            <br />

            <asp:DetailsView ID="DetailsView1" runat="server" Height="400px" Width="745px" 
                AutoGenerateRows="False" DataKeyNames="TS_ID" DataSourceID="SqlDataSource2" 
                EnableModelValidation="True">
                <Fields>

                    <asp:TemplateField HeaderText="Category">
                        <EditItemTemplate>
                            <%--<asp:DropDownList ID="TTCategory" runat="server" DataSourceID="ReqCategoryData" SelectedValue='<%# Bind("TS_NAME") %>' />--%>
                            <asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
                                ID="reqCategoryDropDown" runat="server" AppendDataBoundItems="true" AutoPostBack="true" >                                                            
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>

                    <asp:CommandField ButtonType="Button" EditText="Update" ShowEditButton="True" 
                        ShowCancelButton="True">
                    <ItemStyle HorizontalAlign="Center" />
                    </asp:CommandField>

                </Fields>
            </asp:DetailsView>

        </div>

    </form>
</body>
</html>

在后面的代码中,我正在为下拉列表设置数据源,并使用函数在DB初始加载页面时查询我想要设置为所选值的值的名称:

Partial Class EditFormVB
    Inherits System.Web.UI.Page

    Public Shared category_Name As String = ""
    Dim ddlDataSource As New SqlDataSource

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        DetailsView1.DefaultMode = DetailsViewMode.Edit
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Page.Title = "Editing record"

        ''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)

        ''Set max length of Title field to 70 characters
        Dim dvrTest As DetailsViewRowCollection = DetailsView1.Rows
        Dim TitleTB As TextBox = dvrTest.Item(0).Cells(1).Controls(0)
        TitleTB.Attributes.Add("onkeydown", "isMaxLen(this)")
        TitleTB.Attributes.Add("maxlength", "70")

        Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
        ''Perform dropdown list population operations
        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 using the categoryID 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 //<--this value gets set only when debugging, 
        End If

    End Sub

    Private Function GetDataReader(ByVal sqlText As String) As SqlDataReader
        Dim dr As SqlDataReader
        Dim sqlConn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("TTPRODReportsQuery").ConnectionString)
        sqlConn.Open()
        Dim sqlCmd As SqlCommand = New SqlCommand(sqlText, sqlConn)
        dr = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
        Return dr
    End Function

End Class

下拉列表会正确填充,但是当我尝试设置该值时,它不反映页面加载的时间;只需填充下拉列表,并且在标记中没有设置任何值,因此默认情况下会显示第一个值。奇怪的是,当我调试时,当我单步执行该函数时,该值似乎已设置,就好像一旦函数退出并继续加载页面就会重置selectedvalue。感谢任何帮助或见解

解: 在完成执行后Page_Load后,必须添加一个单独的函数,该函数从DropDownList调用onLoad。仍未解决的问题是DropDownList在Page_Load之后重新绑定。

在HTML中:

<asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
                                ID="reqCategoryDropDown" runat="server" AutoPostBack="true" OnLoad="DDL_DataBound">  

代码背后

Public Shared category_Name As String = ""

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Page.Title = "Editing record"

        ''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)

        ''Set max length of Title field to 70 characters
        Dim dvrTest As DetailsViewRowCollection = DetailsView1.Rows
        Dim TitleTB As TextBox = dvrTest.Item(0).Cells(1).Controls(0)
        TitleTB.Attributes.Add("onkeydown", "isMaxLen(this)")
        TitleTB.Attributes.Add("maxlength", "70")

        Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
        ''Perform dropdown list population operations
        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 using the categoryID 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()
        End If
    End Sub


        Protected Sub DDL_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
            If Page.IsPostBack = False Then
                Dim myDDL As DropDownList = DetailsView1.FindControl("reqCategoryDropDown")
                myDDL.Items.FindByValue(category_Name).Selected = True
            End If
        End Sub

1 个答案:

答案 0 :(得分:2)

为安全起见,您可能需要点击DetailsView_DataBound,并将选择代码放在那里。我想也许数据源控件再次绑定并消除你的选择......