NETRY
NETRY

Reputation: 57

Bind Links To GridView

How can I render links in columns of WebForms GridView?

I have the following code

SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.UsersContacts WHERE UserId='vika'", con);

con.Open();

var list1 = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        var node = reader[1];
        list1.Add(node.ToString());
    }
}
con.Close();

GridView1.DataSource = list1;
GridView1.DataBind();

and I want to do something such as list1.Add("<a href='#'>"+node.ToString()+"<a>"); and make it a link in my GridView.

Upvotes: 0

Views: 99

Answers (1)

Dennis R
Dennis R

Reputation: 3237

I would rather do this at the gridview template definition instead of passing the link from the datasource. Your gridview definition can have the asp:HyperLinkField or asp:HyperLink field and bind the data as required.

<asp:GridView ID="GridView1" runat="server">  
     <Columns>  
            <asp:HyperLinkField   
                HeaderText="View Details"  
                DataNavigateUrlFields="node"  
                DataNavigateUrlFormatString="~/TargetPage.aspx?Id={0}"  
                DataTextField="node"  
                />  
     </Columns>  
</asp:GridView> 

Or

<asp:HyperLink runat="server" NavigateUrl='<%# Eval("node", "~/TargetPage.aspx?Id={0}") %>' Text="View Details" />

Upvotes: 2

Related Questions