C# 在Gridview的BoundField中显示多个数据字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9097283/
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 05:55:36  来源:igfitidea点击:

Display multiple data fields in BoundField of Gridview

c#asp.net

提问by andrew slaughter

I have an asp:GridViewwhich is bound. Within this I have multiple columns, I'm trying to get the data from two database fields concatenated into one field.

我有一个asp:GridView绑定的。在此我有多个列,我试图从连接到一个字段的两个数据库字段中获取数据。

How to do this?

这该怎么做?

Something like this?

像这样的东西?

asp:BoundField DataField="field1 + ' ' + field2" HeaderText="Status" SortExpression="info"

回答by Sree

Try like this. If u are using two datasets make to one datatable and bind it to gridview.

像这样尝试。如果您使用两个数据集制作一个数据表并将其绑定到 gridview。

<asp:BoundField DataField="<%# DataBinder.Eval(Container.DataItem, "f1")%>+ ' ' + <%# DataBinder.Eval(Container.DataItem, "f2")%>" HeaderText="Status" SortExpression="info"/>

回答by pseudocoder

Pretty sure you need to use a TemplateField instead of BoundField for this.

很确定您需要为此使用 TemplateField 而不是 BoundField 。

In your GridView Columns Block:

在您的 GridView 列块中:

    <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
            <%# Eval("FirstName") + " " + Eval("LastName")%>
        </ItemTemplate>
    </asp:TemplateField>

回答by user2703763

ToolTip='<%# Eval("LastName") & "-" & Eval("FirstName") %>'

回答by fubo

Just for completeness, cause I searched a solution and came first here...

只是为了完整性,因为我搜索了一个解决方案并首先来到这里......

You have more flexibility by using string.Format()

您可以通过使用获得更大的灵活性 string.Format()

<asp:TemplateField HeaderText="Status">
 <ItemTemplate>
     <%# string.Format("{0} {1}", Eval("field1") ,Eval("field2"))%>
 </ItemTemplate>
</asp:TemplateField>

Here you can also use the power of string.Format()to format date and number types as descriped here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/formatting-types

在这里,您还可以使用此处所述的string.Format()格式化日期和数字类型的功能:https: //docs.microsoft.com/en-us/dotnet/standard/base-types/formatting-types

Sample:

样本:

<%# String.Format("{0:MM/dd/yyyy} - {1:N2}", Eval("dateValue1"), Eval("decimalValue2")) %>


Another option is to do it in a custom method with code behind

另一种选择是在带有代码的自定义方法中执行此操作

ASPX:

ASPX:

<asp:TemplateField HeaderText="Status">
   <ItemTemplate>
      <asp:Label runat="server" Text='<%#GetStatus(Eval("Status1"),Eval("Status2")) %>'>
      </asp:Label>
   </ItemTemplate>
</asp:TemplateField>

Codebehind:

代码隐藏:

public string GetStatus(object Status1, object Status2)
{
    return (string)Status1 + " " + (string)Status2;
}