Search code examples
asp.netsqlgridviewevaltemplatefield

Format GridView column 2 SQL column values to be separated by a symbol


I have a GridView with one column which contains 2 values from SQL, from columns Author and Author2. In my table there is only one row which has values in both columns, others have only one Author and a NULL. I want to separate only those with both authors with a symbol "&".

I have tried doing this several ways, the first one is with 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>

and the other one:

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

But both resulted in this:
Author &
Author & Author2
Author &

But I want to be able to do this:
Author
Author & Author2
Author

Is there a way to do it?


Solution

  • I would do like this:

    <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>
    

    Here's my test code.

    The markup:

    <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>
    

    The code:

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

    And here's the output:

    enter image description here