c# - 动态添加超链接到gridview

标签 c# asp.net gridview hyperlink

我正在动态生成gridview。这是代码

设计代码

<asp:GridView Width="100%" CssClass="TTable" ID="MainGridView" OnDataBound = "OnDataBound" runat="server" AutoGenerateColumns="False" onrowdatabound="GridView_RowDataBound">
            <Columns>
            </Columns>
</asp:GridView>

背后代码:

private void createGridView(DataTable gridviewdt)
    {
        MainGridView.Columns.Clear();
        //Iterate through the columns of the datatable to set the data bound field dynamically.
        foreach (DataColumn col in gridviewdt.Columns)
        {
            //Declare the bound field and allocate memory for the bound field.
            BoundField bfield = new BoundField();

            //Initalize the DataField value.
            bfield.DataField = col.ColumnName;

            //Initialize the HeaderText field value.
            bfield.HeaderText = col.ColumnName;

            //Add the newly created bound field to the GridView.
            MainGridView.Columns.Add(bfield);

        }

    }

// Bind Datatable to gridview
MainGridView.DataSource = gridviewdt;
MainGridView.DataBind();

在上面的代码中,我想在特定列数据上放置超链接。如果我将超链接直接放在数据表上,那么它会按原样显示,而不执行。

<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>

如何在某些 gridview 列上添加上述链接按钮?

最佳答案

如果我们想在 gridview 控件中以声明方式添加 LinkBut​​ton,那么我们将其包装在 TemplateField 内,而不是在 BoundField 内。另外我不确定你为什么要循环数据表(我猜这是 GridView 的来源)。正确的方法是在将数据绑定(bind)到 gridview 之前将 TemplateField 添加到列集合中,最后在为绑定(bind)的每一行引发的 RowDataBound 事件中添加控件 GridView 。

你可以使用这个:-

Page_Load中:-

if (!IsPostBack)
{
   TemplateField myTemplate = new TemplateField();
   myTemplate.HeaderText = "MyLinkButton";
   MainGridView.Columns.Add(myTemplate);
   BindGrid();
}

这里,BindGrid 是将数据简单地绑定(bind)到您的 gridview 的方法:-

private void BindGrid()
{
   MainGridView.DataSource = GetData(); \\Your data source here
   MainGridView.DataBind();
}

最后在gridview的RowDataBound事件中添加LinkBut​​ton控件,如下所示:-

protected void MainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
       LinkButton myLink = new LinkButton();
       myLink.ID = "LinkButton1";
       myLink.Text = "LinkButton";
       myLink.Click += myLink_Click;
       e.Row.Cells[0].Controls.Add(myLink);
   }
}

请注意,由于我只添加了 1 列(在页面加载中),因此我使用 e.Row.Cells[0] 来获取第一列。如果您添加多个列,那么您将必须相应地更改代码。

关于c# - 动态添加超链接到gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193077/

相关文章:

c# - 在表中,列数据类型为 varchar,使用 linq to sql 仅检索列中数字/数字的值

c# - 快速向 SQL Server 插入 200 万行

c# - 模板字段消失

android - GIF 图片加载缓慢问题

C# 数据读取器 : Sql Batch Of Commands And Return Results

c# - 从 Salesforce.com sObject[] 转换为 .NET DataSet

c# - 上传图像和模型 ASP.NET MVC 4

c# - 使某个网址仅在 48 小时内有效

javascript - 运行 C# 代码后禁用 aspx 页面中的按钮

c# - 如何在 ASP.NET 中编辑、更新和删除 GridView 中的行