C# 如何设置下拉列表 DataTextField 以显示两个数据属性字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9837859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:50:55  来源:igfitidea点击:

How to set drop down list DataTextField to display two data property fields?

c#asp.net

提问by Theomax

I have a drop down list that is populated with data in the code behind. The DataTextFieldattribute is set with the following code:

我有一个下拉列表,其中填充了后面代码中的数据。该DataTextField属性使用以下代码设置:

ddlItems.DataTextField = "ItemName";

I want to display two data properties as the DataTextField. I tried using the following code but it didn't work. And I have researched on the net but couldn't find how to use two data properties.

我想将两个数据属性显示为DataTextField. 我尝试使用以下代码,但没有用。我在网上研究过,但找不到如何使用两个数据属性。

ddlItems.DataTextField = "ItemName" + "ItemDescription";

What code do I need to use to do this?

我需要使用什么代码来做到这一点?

采纳答案by SimpleVar

You can use the Formatting event of ddlItems which will allow you to set logic to how to convert a certain item to a string, or if it makes any sense to use in your program, have a property like RepresentingString that returns Name + Desc, and bind to that property.

您可以使用 ddlItems 的 Formatting 事件,它允许您设置如何将某个项目转换为字符串的逻辑,或者如果在您的程序中使用有任何意义,可以使用 RepresentingString 之类的属性返回 Name + Desc,以及绑定到该属性。

Similar question with more answers and code examples: Format DropDownList.TextValue

带有更多答案和代码示例的类似问题: Format DropDownList.TextValue

回答by SimpleVar

I've achieved this before but I did so using telerik radcombobox (which was capable of including an item template). The template was simply a html table and I seemingly 'concatenated' the two fields. I'm pretty sure the standard asp .net control doesn't have this functionality - but if you look around you will find a 3rd party control that will.

我之前已经实现了这一点,但我使用 Telerik radcombobox(能够包含项目模板)做到了这一点。模板只是一个 html 表,我似乎“连接”了两个字段。我很确定标准的 asp .net 控件没有这个功能——但如果你环顾四周,你会发现一个 3rd 方控件有这个功能。

It is of course possible to deal with this concatenation at the business layer and define a new type (struct is probably best) with a property that contains the two fields as one string.

当然可以在业务层处理这种连接并定义一个新类型(结构可能是最好的),其属性包含两个字段作为一个字符串。

I'm sure there are other ways of achieving this (more efficient ways no doubt), these are just some ways I know of that may help.

我确信还有其他方法可以实现这一点(毫无疑问是更有效的方法),这些只是我所知道的一些可能会有所帮助的方法。

回答by Kris Senden

You can use LinqToSql to make a new datasource containing a displayfield which is formatted, the way you want it to be, like:

您可以使用 LinqToSql 创建一个包含已格式化的显示字段的新数据源,如您希望的那样,例如:

var datasource = from x in products
                 select new {
                     x.Id,
                     x.Code,
                     x.Description,
                     DisplayField = String.Format("{0} ({1})", x.Code, x.Description)
                 };

comboBox.DataSource = datasource;
comboBox.DataValueField = "Id";
comboBox.DataTextField = "DisplayField";
comboBox.DataBind();

回答by cryptic'l

If you're coding with entity framework code-first you could create a new field called NameAndDescriptionand set your ddlItems.DataTextField = "NameAndDescription". The field can be created as follows:

如果您使用实体框架代码优先进行编码,您可以创建一个名为的新字段NameAndDescription并设置您的ddlItems.DataTextField = "NameAndDescription". 该字段可以按如下方式创建:

    public String NameAndDescription
    {
        get { return this.ItemName + this.ItemDescription; }
    }

回答by Syed Adil Hasan

Try this:

尝试这个:

select std.Student_ID,std.Student_Name+' - '+ std.Admission_ID Student_Name 
from Student_tbl std , School_tbl sch 
where sch.School_ID = '" + School_ID + "' and std.Current_Class = '" + Class_ID + "' 
      and std.Section_ID = '" + Section_ID + "'

DL_Student.DataTextField = "Student_Name";
DL_Student.DataValueField = "Student_ID";

回答by Matteo Gaggiano

Starting from a comment on Format DropDownList.TextValueI learned about DataColumn.Expression (DataColumn.Expression Propertyso this may be a valid solution (In my case it was perfect):

从对Format DropDownList.TextValue的评论开始,我了解了 DataColumn.Expression (DataColumn.Expression 属性,因此这可能是一个有效的解决方案(在我的情况下它是完美的):

DataColumn title = new DataColumn();
title.ColumnName = "Title";
title.DataType = System.Type.GetType("System.String");
title.Expression = "ItemName + ' - ' + ItemDescription";
dataTable.Columns.Add(title);

// Or in one line

dataTable.Columns.Add(new DataColumn("Title", System.Type.GetType("System.String"), "ItemName + ' - ' + ItemDescription"));

ddlItems.DataSource = dataTable;
ddlItems.DataTextField = "Title";
ddlItems.DataValueField = "Id";
ddlItems.DataBind();

回答by ali bencharda

The following code worked for me:

以下代码对我有用:

select id, ItemName + ' - ' + ItemDescription as 'yournamecolumn' from `yourtable`
ddlItems.DataTextField = "yournamecolumn";
ddlItems.DataValueField = "id";
ddlItems.DataBind();

回答by Davezilla

I have done something similar to this in two ways: either in C# or SQL.

我已经通过两种方式完成了类似的事情:在 C# 或 SQL 中。

Matteo Gaggiano below gives a good example of the C# method:

下面的 Matteo Gaggiano 给出了 C# 方法的一个很好的例子:

dataTable.Columns.Add(new DataColumn("Title", System.Type.GetType("System.String"), "ItemName + ' - ' + ItemDescription"));

ddlItems.DataSource = dataTable;
ddlItems.DataTextField = "Title";
ddlItems.DataValueField = "Id";
ddlItems.DataBind();

Or it can be done in SQL:

或者它可以在 SQL 中完成:

SELECT ItemName + ' - ' + ItemDescription AS Title FROM yourSQLtable

and then using the last four lines above in the C# code.

然后在 C# 代码中使用上面的最后四行。

回答by ali mahmoodi

Simplest way is in .aspx file :

最简单的方法是在 .aspx 文件中:

<asp:DropDownList ID="ddlItems" runat="server" DataSourceID="YourDataSource" DataTextField='<%# Eval("Id")+" - "+Eval("Title") %>' ..... />

Hope useful.

希望有用。

回答by Tommaso

just fill in the dropdownlist from code behind

只需从后面的代码填写下拉列表

HTML

HTML

<asp:DropDownList ID="ddlSample" runat="server"></asp:DropDownList>

VB.NET

网络

        Dim Conn As SqlConnection
        Dim Comm As SqlCommand
        Dim Read As SqlDataReader

        Conn = New SqlConnection()
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings("Read").ConnectionString

        Comm = New SqlCommand()
        Comm.CommandType = CommandType.Text
        Comm.CommandText = "SELECT * FROM TABLE"
        Comm.Connection = Conn
        Comm.Connection.Open()

        Read = Comm.ExecuteReader()
        ddlSample.Items.Insert(0, New ListItem("Seleziona", ""))
        While Read.Read()
            ddlSample.Items.Insert(1, New ListItem(Read("ID") & " - " & Read("Desc")), ReadLivelli("ID")))
        End While

        Read.Close()
        Comm.Connection.Close()
        Comm.Dispose()
        Conn.Dispose()