【问题标题】:How to set selected value on a databound dropdownlist from a datatable如何在数据表中的数据绑定下拉列表上设置选定值
【发布时间】:2016-05-19 21:02:33
【问题描述】:

好的,所以我有一个最初从数据库填充的下拉列表。现在基于数据表,我希望所选值等于数据库中的文本。无论我做什么,它只显示“---选择一个---”这是我手动添加到下拉列表项目列表中的唯一项目,如果我拉的值为空(或者这就是我想要的),则显示默认值做)

 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();
        }
    }

aspx 页面中的DropDownList。

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

sql 数据源选择命令。

SELECT [Category_Name] FROM [Category]

编辑:这是完整的代码,但我不知道它是否相关,抱歉。

【问题讨论】:

  • 你能提供给我们完整的 cade 吗?你确定你的下拉列表的数据绑定是在你的 page_load 之前完成的吗?
  • 总是故意选择第一行?
  • 也许你可以尝试在 pre_render 函数中进行。您复制下面提供的代码作为答案,但不是在 page_load 中复制它,而是在 pre_render 中复制它
  • protected void Page_PreRender(object sender, EventArgs e) {...} Page Life Cycle
  • 您也可以使用 SelectedValue 代替 SelectedItem。 CategoryDropDownList.SelectedValue = DT.Rows[0]["Category_Name"].ToString()

标签: c# asp.net drop-down-menu


【解决方案1】:

改变:

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

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

【讨论】:

    【解决方案2】:

    两件事:

    1. 不要在 ASP.NET 中使用全局连接(至少不要将它们设为静态),因为它是一个多线程环境。而是始终使用using-statement 尽快关闭连接
    2. if(!IsPostback) 签入Page_Load,当EnableViewState 设置为true(默认)时,不要在回发时绑定控件。否则不会触发事件并且值(如DropDownList-SelectedIndex)会被覆盖。

    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));
            }
        }
    }
    

    【讨论】:

    • survey_desc 填充备忘录没问题,但类别下拉列表仍然没有做任何事情。
    • @BasharKH: 你真的需要使用SqlDataSource 控件吗?(我不会在生产中使用它,而是在演示页面中使用它)而是在之前的if(!IsPostBack) 代码中手动绑定它CategoryDropDownList.SelectedIndex 部分。
    • 我刚做了这个,它起作用了 CategoryDropDownList.SelectedValue = DT.Rows[0]["Category_Name"].ToString();
    • @BasharKH:是的,如果您的DataTextFieldDataValueField 相同。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      相关资源
      最近更新 更多