ASP DotNet

ASP DotNet

  • NA
  • 2
  • 3.7k

Repopulate Dropdown list with selected value

Dec 17 2012 5:01 PM
Reselecting values in a Dropdown populating from database

Cosider an example where we have Data Insert form with a Dropdown list populated dynamically.

On my.aspx page
<asp:FormView id="f1" runat="server" DefaultMode="Insert">
<asp:DropDownList ID="cats" runat="server" />
</asp:FormView>
--

On code behind
inserts ins = new inserts();
DropDownList ddl = (DropDownList)f1.FindControl("cats");
ddl.DataSource = ins.getall2();
ddl.DataTextField = "book_categories_name";
ddl.DataValueField = "book_categories_id";
ddl.DataBind();
--

On the user defined data access class file named APP_CODE/inserts.cs

public List<inserts> getall2()
    {
        List<inserts> result = new List<inserts>();
        SqlConnection conn = new SqlConnection(_connectionstring);
        SqlCommand cmd = new SqlCommand("Select book_categories_name, book_categories_id from book_categories1 order by book_categories_name DESC", conn);
        using (conn)
        {
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                inserts ins = new inserts();
                ins.book_categories_name = Convert.ToString((dr["book_categories_name"]).ToString());
                ins.book_categories_id = Convert.ToInt16(dr["book_categories_id"].ToString());
                result.Add(ins);

            }
            return result;
        }

    }
--

Above code Populates the Dropdown list  with the appropriate values.

This my.aspx page has a submit button which when pressed inserts the "book_categories_id" which is selected above into a details table named details.


++Now this is what i need as below+++
On another page named edit.aspx i will be editing vaues that i just entered.
I basically want to repopulate the values and auto select the value entered for that record.