title: Set dropdownlist selected value on initial page load
body: <p>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):</p>
  
  <pre><code> &lt;%@ Page Language="VB" CodeFile="EditFormVB.aspx.vb" Inherits="EditFormVB" %&gt;
  &lt;%@ Register Namespace="CustomBoundField" TagPrefix="custom" %&gt;
  
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head runat="server"&gt;
      &lt;title&gt;Edit Pop-up&lt;/title&gt;
  &lt;/head&gt;
  &lt;body class=""&gt;
      &lt;form id="form1" runat="server"&gt;
          &lt;div&gt;
  
              &lt;script  type="text/javascript"&gt;
                  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();
                  }
              &lt;/script&gt;
  
              &lt;asp:ScriptManager ID="ScriptManager2" runat="server" /&gt;
              &lt;telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" DecoratedControls="All" /&gt;
              &lt;br /&gt;
              &lt;br /&gt;
  
              &lt;asp:DetailsView ID="DetailsView1" DataKeyNames="ID" runat="server" AutoGenerateRows="False"
                  GridLines="None" DataSourceID="detailsSqlDataSource" Height="50px" Width="125px"
                  BorderWidth="0" CellPadding="0" CellSpacing="7"&gt;
              &lt;Fields&gt;
                  &lt;asp:BoundField DataField="TS_DESCRIPTION" HeaderText="TS_DESCRIPTION" SortExpression="TS_DESCRIPTION" /&gt;
                  &lt;asp:BoundField DataField="TS_TITLE" HeaderText="TS_TITLE" SortExpression="TS_TITLE" /&gt;
                  &lt;asp:CommandField ShowEditButton="True" /&gt;
                  &lt;asp:CommandField ShowInsertButton="True" /&gt;
              &lt;/Fields&gt;
              &lt;/asp:DetailsView&gt;--%&gt;
  
              &lt;telerik:RadScriptManager ID="RadScriptManager1" runat="server" /&gt;
              &lt;telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" Skin="Vista" /&gt;
              &lt;br /&gt;
              &lt;br /&gt;
  
              &lt;asp:DetailsView ID="DetailsView1" runat="server" Height="400px" Width="745px" 
                  AutoGenerateRows="False" DataKeyNames="TS_ID" DataSourceID="SqlDataSource2" 
                  EnableModelValidation="True"&gt;
                  &lt;Fields&gt;
  
                      &lt;asp:TemplateField HeaderText="Category"&gt;
                          &lt;EditItemTemplate&gt;
                              &lt;%--&lt;asp:DropDownList ID="TTCategory" runat="server" DataSourceID="ReqCategoryData" SelectedValue='&lt;%# Bind("TS_NAME") %&gt;' /&gt;--%&gt;
                              &lt;asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
                                  ID="reqCategoryDropDown" runat="server" AppendDataBoundItems="true" AutoPostBack="true" &gt;                                                            
                              &lt;/asp:DropDownList&gt;
                          &lt;/EditItemTemplate&gt;
                      &lt;/asp:TemplateField&gt;
  
                      &lt;asp:CommandField ButtonType="Button" EditText="Update" ShowEditButton="True" 
                          ShowCancelButton="True"&gt;
                      &lt;ItemStyle HorizontalAlign="Center" /&gt;
                      &lt;/asp:CommandField&gt;
  
                  &lt;/Fields&gt;
              &lt;/asp:DetailsView&gt;
  
          &lt;/div&gt;
  
      &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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 //&lt;--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
  </code></pre>
  
  <p>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</p>
  
  <p>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.</p>
  
  <p>IN HTML:</p>
  
  <pre><code>&lt;asp:DropDownList DataSourceID="ReqCategoryData" DataTextField="ReqCategory" DataValueField="ReqCategory"
                                  ID="reqCategoryDropDown" runat="server" AutoPostBack="true" OnLoad="DDL_DataBound"&gt;  
  </code></pre>
  
  <p>IN CODE-BEHIND</p>
  
  <pre><code>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
  </code></pre>