简体   繁体   English

如果也有DataTextValueField,asp.net dropdownlist不显示DataTextField

[英]asp.net dropdownlist not showing DataTextField if there is a DataTextValueField too

I have a DataValueField and a DataTextField in my DropDownList . 我的DropDownList有一个DataValueField和一个DataTextField The data is from a DataSet and I want the dropdownlist to show the text field of my Dataset as preselected text. 该数据是从一个DataSet ,我想在dropdownlist显示我的文本字段Dataset作为预选文本。 The Dataset is filled with data from a mysql table , containing " id " and " text ". Dataset填充有来自mysql table数据,其中包含“ id ”和“ text ”。 The DropDownList code is: DropDownList代码为:

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

If there is no DataValueField -Tag the DropDownList shows correctly the text-value from my DataSet as preselected text in my DropDownList . 如果没有DataValueField -Tag的DropDownList正确显示从我的文本值DataSet在我的预选文本DropDownList But if I add the DataValueField the DataTextField doesnt showing any preselected Text in the DropDownList . 但是,如果我添加DataValueFieldDataTextField不会在DropDownList显示任何预选的文本。

The code for the data is: 数据的代码为:

//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, " ");

How can I use both, the DataValueField and the DataTextField ? 如何同时使用DataValueFieldDataTextField

Try something like this 试试这个

Code: 码:

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

Markup 标记

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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