title: Assign Selected Value in DropDown from Variable
body: <p>I have a dropdown list of page numbers that gets the correct values from a database query depending. Everything works correctly with this list except I can't seem to figure out how to retain the selected value in the dropdown. The page number is passed via a querystring and I'm retaining that as a ViewState variable. I can confirm that this variable is correctly retained by returning it the .aspx. How to I set that value as the selected though so the dropdown doesn't always revert to "1" when a new page is loaded?</p>
  
  <p>My code behind:</p>
  
  <pre><code>public string proc;
  
  public string page
  {
      get { return ViewState["page"] as string; }
      set { ViewState["page"] = value; }
  }
  
  protected void Page_Load(object sender, EventArgs e)
  {
      page = Request.QueryString["page"];
      Page_Numbers();
  }
  
  public void Page_Numbers()
  {
      if (proc != null)
      {
          int totalRows;
          int totalPages;
  
          string sqlConn = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
          SqlConnection sqlConnection1 = new SqlConnection(sqlConn);
          SqlCommand cmd = new SqlCommand();
  
          cmd.CommandText = (proc);
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Connection = sqlConnection1;
  
          sqlConnection1.Open();
          totalRows = Convert.ToInt32(cmd.ExecuteScalar());
          totalPages = ((totalRows / 1000) + 1);
          sqlConnection1.Close();
  
          for (int i = 1; i &lt;= totalPages; i++)
          {
              PageDdl.Items.Add(new ListItem(i.ToString()));
  
              if (i == Convert.ToInt32(page))
              {
                  PageDdl.SelectedItem.Value = page;
              }
          }
      }
  }
  
  protected void PageDdl_SelectedIndexChanged(object sender, EventArgs e)
  {
      Response.Redirect("report.aspx?proc=" + proc + "&amp;page=" + PageDdl.SelectedItem.Text);
  }
  </code></pre>
  
  <p>My aspx:</p>
  
  <pre><code>        &lt;div class="totalPages"&gt;   
              &lt;asp:DropDownList ID="PageDdl" runat="server" 
                  onselectedindexchanged="PageDdl_SelectedIndexChanged" 
                  AutoPostBack="True" Visible="True"&gt;
              &lt;/asp:DropDownList&gt;
          &lt;/div&gt;
          Page: &lt;%=page %&gt;
  </code></pre>
  
  <p>On my aspx, <em>page</em> variable is displayed so I can confirm it is assigned correctly.</p>