jkjk
jkjk

Reputation: 5937

Hyperlink a column in gridview

I'm using boundfield to display columns:

<Columns>
<asp:BoundField  DataField=”AccountCode” HeaderText=”Account Code”>
    <ItemStyle Font-Size=”Large” />
</asp:BoundField>
<asp:BoundField  DataField=”AccountName” HeaderText=”Account Name”      
        FooterText=”Enter Footer Text”>
    <FooterStyle CssClass=”FooterStyle” />
</asp:BoundField >
<asp:BoundField  DataField=”Type” HeaderText=”Account Type” />

I have 4 types of accounts (a, b, c , or d). I would like to hyperlink the account type column based on the 4 different account types. Basically, I would like to link to one of the 4 different webpages depending on which type of account was selected. I'm using C# in Visual Studio 2010. Any help would be greatly appreciated.

Upvotes: 0

Views: 172

Answers (2)

Andrei
Andrei

Reputation: 56688

Use HyperLinkField for that:

<asp:HyperLinkField HeaderText="Account Type"
    DataTextField="Type"
    DataTextFormatString="{0}"
    DataNavigateUrlFields="TypeID"
    DataNavigateUrlFormatString="~\AccountType.aspx?type={0}"          
    Target="_blank" />

or, if you have completely different URLs for different account types, use TemplateField. Since URL selection involves some logic, I've moved it to code behind here.

<asp:TemplateField HeaderText="Account Type">
    <ItemTemplate>
        <asp:HyperLink runat="server"
            Text="Type"
            NavigateUrl='<%# GetAccountTypeUrl(Eval("Type")) %>' />
    </ItemTemplate>
</asp:TemplateField>

And method GetAccountTypeUrl in code behind:

protected string GetAccountTypeUrl(object typeName)
{
    string type = typeName as string;

    switch (type)
    {
        case "a":
            return "url_a";
        case "b":
            return "url_b";
        case "c":
            return "url_c";
        case "d":
            return "url_d";
        default:
            return string.Empty;
    }
}

Upvotes: 1

codingbiz
codingbiz

Reputation: 26376

Try the following

instead of <asp:BoundField DataField=”Type” HeaderText=”Account Type” /> use

<asp:TemplateField HeaderText="Account Type">
<ItemTemplate>
   <a href='<%# String.Format("~/AccountType.aspx?type={0}", Eval("Type")) %>'><%# Eval("Type") %></a>
</ItemTemplate>
</asp:TemplateField>

Upvotes: 0

Related Questions