如何在网格视图中为按钮字段创建单击事件 asp.net

本文关键字:创建 字段 单击 事件 net asp 按钮 网格 视图 | 更新日期: 2023-09-27 18:31:27

我从代码隐藏中动态地创建了.aspx GridView。我在那个GridView中插入了一个sql表。然后我又添加了一个按钮归档列。这是代码:

ButtonField bf = new ButtonField();
bf.Text = "Details";
bf.ButtonType = ButtonType.Button;
DataTable table = new DataTable();
table.Load(reader);
GridView gv = new GridView();
gv.Columns.Add(bf);
gv.DataSource = table;
gv.DataBind();

现在我想在这个按钮字段上添加一个MouseClickEvent,但没有属性ClickMouseClick。有什么办法可以做到这一点吗?

如何在网格视图中为按钮字段创建单击事件 asp.net

对于GridView内部的ButtonField,您可以指定CommandName

bf.CommandName = "MyCommand";

并像这样访问它:

void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "MyCommand")
    {
    }
}

您可能会发现它很有用:ButtonField.CommandName Property。

当涉及到每行都有一个动作(如编辑按钮或详细信息)的网格视图时,我个人喜欢执行以下操作:

  1. 在 GridView 之后有一个隐藏的按钮,此按钮有一个 onclick 事件(假设 OnDetailsButtonClick )。因此,此按钮是将进行提交的按钮。
  2. 创建一个隐藏字段,单击行中的操作时将填充该字段,以便服务器端代码将选取执行操作的 rowId
  3. 使网格视图中的每个按钮都具有OnClientClick(假设名为goToDetails(entityId)的javascript函数)所以JavaScript函数将看起来像:
function goToDetails(entityId){
    $("#HiddenEntityId").val(entityId);
    $("#Button").click()
}

从后面的代码中,您可以从隐藏字段中获取行/实体 ID:

private void OnDetailsButton_Click(object sender, EventArgs e){
   string entityId = HiddenEntityId.Value;
   //now you can do whatever you like
}

您必须使用"Gridview.RowCommand"句柄来为ButtonField中的按钮启用自定义脚本。

1) 将"命令名称"

属性添加到按钮字段,此示例假定命令名称 ="删除"

2)

    Protected Sub GridView1_buttonsclicked(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
    If e.CommandName = "Delete" Then
        'Delete clicked with index of " + e.CommandArgument.ToString
        'Your code here, using the e.commandargument as the gridview index, then select column values using that index.
    End If
End Sub