2014-01-11 46 views
0

我有一列GridView,其中一列包含来自SQL的两个值,来自Author和Author2列。 在我的表中只有一行在两列中都有值,其他的只有一个作者和一个NULL。我只想将两位作者的符号分别为“&”。格式GridView列2要用符号分隔的SQL列值

我试图这样做几种方式,第一种是用CSS:

<head> 
<style> 
.label2css:before { 
content: "& "; 
} 
</style> 
</head> 

...

<ItemTemplate> 
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Author") %>'></asp:Label> 
<asp:Label ID="Label2" CssClass="label2css" runat="server" Text='<%# Eval("Author2") %>'></asp:Label> 
</ItemTemplate> 

,另一种:

<ItemTemplate> 
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Author") %>'></asp:Label> 
<asp:Label ID="Label2" runat="server" Text='<%# "&" + Eval("Author2") %>'> </asp:Label> 
</ItemTemplate> 

但两者导致:
作者&
作者& Author2
作者&

但我希望能够做到这一点:
作者
作者& Author2
作者

有没有办法做到这一点?

+0

如果我没记错的话应该有一种方法来使用databind事件来操纵输出。这样,您可以在后面的代码中检查null,并根据需要设置author2的值。 – surfmuggle

回答

1

我会做这样的:

<ItemTemplate> 
    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Author") %>'></asp:Label> 
    <asp:Label ID="Label2" runat="server" Text='<%# String.IsNullOrEmpty(Eval("Author2") as string) ? "" : Eval("Author2", "& {0}") %>'> </asp:Label> 
</ItemTemplate> 

这里是我的测试代码。

的标记:

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"> 
    <Columns> 
     <asp:TemplateField> 
      <ItemTemplate> 
       <asp:Label ID="Label1" runat="server" Text='<%# Bind("Author") %>'></asp:Label> 
       <asp:Label ID="Label2" runat="server" Text='<%# String.IsNullOrEmpty(Eval("Author2") as string) ? "" : Eval("Author2", "& {0}") %>'> </asp:Label> 
       </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

代码:

public partial class WebForm3 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

     GridView1.DataSource = new List<MyClass>(){ 
      new MyClass { Author="Author"}, 
      new MyClass { Author="Author", Author2="Author2"}, 
      new MyClass { Author="Author"} 

     }; 

     GridView1.DataBind(); 
    } 
} 

public class MyClass 
{ 
    public string Author { get; set; } 
    public string Author2 { get; set; } 
} 

而这里的输出:

enter image description here

0

谢谢,@afzalulh!我能够这样做你的代码是这样的:

protected void Page_Load(object sender, EventArgs e) 
{ 
    GridView1.DataSource = SqlDataSource1; 
    GridView1.DataBind(); 
}