Mudassir Hasan
Mudassir Hasan

Reputation: 28771

How to create columns dynamically in a asp:gridview

I want to make a column in Gridview whose values acts as a hyperlink. The hyperlink url is made up of parts supplied from dataset

Foreach(dRow in Tables[0].Row)
{
url = "<a href=ClientView.aspx?\"" + dRow["client_id"].ToString() +"</a>";
}

How can I generate column in gridview which shows this link ?

Other columns are defined in markup.

<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False">

<Columns>
     <asp:BoundField DataField="Sno" HeaderText="SNo" />
     <asp:BoundField DataField="ClientName" HeaderText="Name" />
</Columns>
</asp:GridView>

I want to add column ClientId between gridview's SNo and ClientName column whose text is obtained from dataset row drow["clientid"] field and is enclosed between anchor tags to behave like url.

Upvotes: 2

Views: 2087

Answers (2)

Praveen Nambiar
Praveen Nambiar

Reputation: 4892

Well to add to your existing code, add a templatefield.

<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Sno" HeaderText="SNo" />
        <asp:BoundField DataField="ClientName" HeaderText="Name" />
        <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton runat="server" id="gvlbtnClientVIew"
              PostBackUrl='<%# "ClientView.aspx?client_id=" + Eval("client_id") %>'
              Text='<%# Bind("client_id") %>'>
            </asp:LinkButton>
        </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView>

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

Use a TemplateField in your header, you don't need to create it dynamically:

<asp:GridView runat="server" ID="gridView1" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:hyperlink runat="server" id="hlClientView"
                  NavigateUrl='<%# String.Format("ClientView.aspx?client_id={0}", Eval("client_id")) %>'
                  Text='<%# Eval("client_id") %>'>
                </asp:hyperlink>
            </HeaderTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Upvotes: 5

Related Questions