我正在动态生成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 控件中以声明方式添加 LinkButton
,那么我们将其包装在 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
事件中添加LinkButton
控件,如下所示:-
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/