【问题标题】:asp.net dropdownlist not showing DataTextField if there is a DataTextValueField too如果也有 DataTextValueField,asp.net 下拉列表不显示 DataTextField
【发布时间】:2013-04-12 11:45:30
【问题描述】:

我的DropDownList 中有一个DataValueField 和一个DataTextField。数据来自DataSet,我希望dropdownlistDataset 的文本字段显示为预选文本。 Dataset 填充了来自 mysql table 的数据,其中包含“id”和“text”。 DropDownList 代码为:

<asp:DropDownList runat="server" DataValueField="id" 
DataTextField="text" ID="statusList" CssClass="viewItemRight" 
AutoPostBack="true"></asp:DropDownList>

如果没有DataValueField-标记DropDownList 将我的DataSet 中的文本值正确显示为我DropDownList 中的预选文本。但是如果我添加DataValueField DataTextField 不会在DropDownList 中显示任何预选文本。

数据的代码是:

//load statusList
            cmd = new MySqlCommand();
            cmd.CommandText = "SELECT * FROM statuslist WHERE active = '1' ORDER BY sorting ASC";
            cmd.Connection = con;
            sda = new MySqlDataAdapter(cmd);
            ds = new DataSet();
            sda.Fill(ds);
            statusList.DataSource = ds;
            statusList.DataBind();
            statusList.Items.Insert(0, " ");

如何同时使用DataValueFieldDataTextField

【问题讨论】:

  • 你从哪里填充这个下拉列表..所以它的代码..如果你从数据库填充...显示你的数据库模式..
  • 添加了代码,但我认为代码不是问题
  • 它的 bcz u 在 0 索引处插入 " " 项

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


【解决方案1】:

试试这样的

代码:

DataTable dt = populatedd();
   statusList.DataSource = dt;
   statusList.DataTextField = "name";
   statusList.DataValueField = "id";
   statusList.DataBind();

    public DataTable populatedd()
    {
        string myQuery = "select id,name from yourtable order by name";
        SqlDataAdapter dap = new SqlDataAdapter(myQuery, con);
        DataSet ds = new DataSet();
        dap.Fill(ds);
        return ds.Tables[0];
    }

标记

<asp:DropDownList runat="server" ID="statusList" CssClass="viewItemRight" 
AutoPostBack="true"></asp:DropDownList>

【讨论】:

  • @user1814545: 快乐编码:)
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 2013-10-18
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多