views:

33

answers:

1

I posted a similar question previously, but none of the answers worked and I've been scouring all over the web trying to find a solution. My situation, I have a Edit Window webform with a dropdownlist (Note: to avoid confusion, I'm using Telerik extensions only to decorate the 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"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<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>

And in the code behind, I'm setting the datasource for the dropdownlist and using a function to query the DB for the name of the value I want to set as the selected value when the page loads initially:

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

The dropdownlist does get populated appropriately, however when I attempt to set the value, it doesn't reflect when the page loads; the dropdownlist just gets populated and no value is set to selected in the markup, so the first value is shown by default. The odd thing is that when I'm debugging, the value appears to get set when I step through the function, it's as if the selectedvalue is getting reset as soon as the function exits and proceeds to load the page. Any help or insight is appreciated

SOLUTION: Had to add a separate function that is called onLoad from the DropDownList after the after Page_Load is done executing. Still unresolved is why the the DropDownList rebinds after the Page_Load.

IN HTML:

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

IN CODE-BEHIND

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
A: 

Hey,

For safety sake, you may want to tap into DetailsView_DataBound, and put your selection code there. I think maybe the data source control is binding again and wiping out your selection...

Brian
Hey Brian, how exactly do I tap into DetailsView_Databound from the a code-behind? Could you provide some details?? Thanks
kingrichard2005
Created and used the DetailsView_Databound function, but still didn't work.
kingrichard2005
OK, with the new code, could you update the code-sample above, so that I can see what the new code looks like? Typically, the reasons for the error you are getting is that something later in the process either: 1) rebinds the data source, potentially clearing the data source or 2) sets the value to something else, or 3) the binding code works on every page load, and value's aren't retained on postback.
Brian
Hey Brian, finally was able to get it working. You were right that something was causing the dropdownlist to rebind to the data source after the Page_Load function executed, still not sure what's causing it. I added a method that the dropdownlist calls onLoad that sets a shared variable where the category name is stored as the selected value. I added the solution code above for anyone else experiencing this problem.
kingrichard2005