R – ASP.net 2.0 GridView Columns dependant on multiple columns in the bound result set


I'm working with an ASP.net 2.0 GridView control that is bound to the results of a sql query, so it looks something like this:

<asp:GridView ID="MySitesGridView" runat="server" AutoGenerateColumns="False" DataSourceID="InventoryDB" AllowSorting="True" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand" OnRowDataBound="siteRowDataBound">
            <asp:BoundField DataField="Server" HeaderText="Server"/>
            <asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" />
            <asp:BoundField DataField="PublicIP" HeaderText="Site Address" DataFormatString="&lt;a href='http://{0}/foo'&gt;Go To Site&lt;/a&gt;" />

As you can see, I'm displaying links with addresses in one of the columns (the one bound to the PublicIP field) using the format string:

&lt;a href='http://{0}/foo'&gt;Go To Site&lt;/a&gt;

Here's the problem: I need to use one of the other columns from the result set as well as the PublicIP column in my links, but I don't know how to make that available to my format string. I essentially need that column bound to two columns from the result set. To clarify, I need something like:

&lt;a href='http://{0}/{1}'&gt;Go To Site&lt;/a&gt;

Where {1} is the value of my other column. Is there any way to accomplish this cleanly (even if it doesn't use format strings)? I've looked into using TemplateFields as well, but can see no easy way to do it with them either.

Best Solution

TemplateFields are the way to go.

I usually prefer to have a private string function in the Page which I pass several object variables, and calculate the resulting string.

<a href="<%# CalculateUrl(Eval("PublicIP"), Eval("Customer")) %>">site</a>

and in the code-behind:

private string CalculateUrl(object PublicIP, object Customer)
    if (PublicIP==null || PublicIP==DBNull.Value)
        return "";
    if (Customer==null || Customer==DBNull.Value)
        return "";
    return "http://" + PublicIP.ToString() + "/" + Customer.ToString();

Advantage is that the function can be shared in a common parent class, or as a static public function of a utility class.

Related Question