简体   繁体   中英

How to set selected value on a databound dropdownlist from a datatable

Ok, so i have a dropdownlist that is originally populated from the database. Now based on a datatable, i want the selected value to be equal to the text residing in the database. Whatever i do, it only shows "---Select One---" which is the only item i added manually to the dropdownlist items list to show a default value if the value i'm pulling is null (or that's what i want to do)

 protected void Page_Load(object sender, EventArgs e)
    {
        Master.TopLabel = "Survey Creation";
        if (!IsPostBack)
        {

            SqlConnection Connection = DatabaseConnection.GetSurveySystemConnection();

            string sqlquery = "SELECT S.[Survey_Desc], S.[Start_Date], C.[Category_Name] ,S.[End_Date], S.[Audience] FROM [Survey] S  Inner Join Category C On S.Category_ID = C.ID Where S.[ID] =" + Session["Survey_ID"];

            SqlCommand cmd = new SqlCommand(sqlquery, Connection);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataTable DT = new DataTable();
            da.Fill(DT);

            if (DT != null)
            {
                DescriptionMemo.Text = DT.Rows[0]["Survey_Desc"].ToString();
                CategoryDropDownList.SelectedIndex = CategoryDropDownList.Items.IndexOf(CategoryDropDownList.Items.FindByText(DT.Rows[0]["Category_Name"].ToString()));
                StartDateCalender.SelectedDate = DateTime.Parse(DT.Rows[0]["Start_Date"].ToString());
                EndDateCalender.SelectedDate = DateTime.Parse(DT.Rows[0]["End_Date"].ToString());
                string Audience = DT.Rows[0]["Audience"].ToString();
                if (Audience == "Students Only")
                {
                    AudienceRadioGroup.Items[0].Selected = true;
                }
                else if (Audience == "Staff Only")
                {
                    AudienceRadioGroup.Items[1].Selected = true;
                }
                else
                {
                    AudienceRadioGroup.Items[2].Selected = true;
                }


            }
          Connection.Close();
        }
    }

DropDownList in aspx page.

<asp:DropDownList ID="CategoryDropDownList" runat="server" 
                    DataSourceID="SqlDataSource1" DataTextField="Category_Name" 
                    DataValueField="Category_Name" AppendDataBoundItems="true" Height="16px" 
                    Width="200px">
                    <asp:ListItem>---Select One---</asp:ListItem>
                </asp:DropDownList>

The sql datasource select command.

SELECT [Category_Name] FROM [Category]

EDIT : This is full code, but i didnt know if it was relevant, sorry.

Change :

CategoryDropDownList.SelectedIndex = CategoryDropDownList.Items.IndexOf(CategoryDropDownList.Items.FindByText(DT.Rows[0]["Category_Name"].ToString()));

to

CategoryDropDownList.SelectedValue = DT.Rows[0]["Category_Name"].ToString()

Two things:

  1. don't use a global connection in ASP.NET (at least, don't make them static)since it is a multi threading environment. Instead always close connections as soon as possible best by using the using-statement
  2. put an if(!IsPostback) check into Page_Load , don't databind controls on postback when EnableViewState is set to true (default). Otherwise events won't be triggered and values(like DropDownList-SelectedIndex ) are overridden.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        string sqlquery = "SELECT S.[Survey_Desc], C.[Category_Name], FROM [Survey] S  Inner Join Category C On S.Category_ID = C.ID Where S.[ID] =" + Session["Survey_ID"];
        using(var con=new SqlConnection(connectionString))
        using(var cmd = new SqlCommand(sqlquery, con))
        using(var da = new SqlDataAdapter(cmd))
        {
            DataTable DT = new DataTable();
            da.Fill(DT);
            DescriptionMemo.Text = DT.Rows[0].Field<string>("Survey_Desc");
            string categoryName = DT.Rows[0].Field<string>("Category_Name");
            CategoryDropDownList.SelectedIndex = CategoryDropDownList.Items
                .IndexOf(CategoryDropDownList.Items.FindByText(categoryName));
        }
    }
}

OnPageLoad CategoryDropDownList.Items.FindByText(categoryName).selected = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM