Bind Links To GridView

血红的双手。 提交于 2019-12-24 22:32:32

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/24291922/bind-links-to-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!