You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何为DataGrid添加LinkButton列并绑定点击触发事件

DataGrid LinkButton按钮列点击事件实现方案
  • 第一步:修改前端DataGrid声明代码
    将原ButtonColumn的ButtonType属性改为LinkButton,同时为DataGrid添加OnItemCommand属性绑定事件处理方法,修改后代码如下:
<asp:DataGrid ID="grdNipr" runat="server" CssClass="dataTable" AllowPaging="true" OnItemCommand="grdNipr_ItemCommand">                                                                                                      
    <Columns>
        <asp:ButtonColumn 
            Text="Approve" 
            ButtonType="LinkButton"   
            HeaderText="Approve" 
            CommandName="ApproveButton" /> 
    </Columns>                                 
</asp:DataGrid>
  • 第二步:编写后台事件处理代码
    在对应的.cs后台文件中添加如下事件处理方法,可根据需要在方法内实现对应的业务逻辑,也可通过e.Item.ItemIndex获取当前点击的行索引,读取行内其他字段数据:
protected void grdNipr_ItemCommand(object source, DataGridCommandEventArgs e)
{
    // 判断触发事件的按钮是否为审批按钮
    if (e.CommandName == "ApproveButton")
    {
        // 此处编写你的业务逻辑,示例:获取当前点击行的索引
        int currentRowIndex = e.Item.ItemIndex;
        // 如需获取行内其他单元格数据,可使用如下写法,索引对应列的顺序
        string cellValue = e.Item.Cells[0].Text;
        
        // 你的业务逻辑代码...
    }
}
  • 特别注意:如果你的DataGrid是在Page_Load方法中绑定数据,必须将绑定逻辑放在!IsPostBack判断内,否则点击按钮时页面会重新绑定数据,导致事件无法触发,示例如下:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // 此处编写DataGrid的绑定逻辑
        grdNipr.DataSource = 你的数据源;
        grdNipr.DataBind();
    }
}

内容的提问来源于stack exchange,提问作者Rao Burhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 22:54:03