Asp.net动态网格视图按钮

本文关键字:视图 按钮 网格 动态 net Asp | 更新日期: 2023-09-27 18:13:56

我有一个gridview,从SQL填充的数据,我想动态地添加按钮/链接按钮到它的列。

protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            Button button = new Button();
            button.ID = "row" + e.Row.RowIndex;
            button.Text = "click me";
            button.Click += new EventHandler(Unnamed_Click);
            e.Row.Cells[1].Controls.Add(button);
        }

视觉效果很好,但是当单击它时,它会回发,并且更改会丢失。按钮不见了。

我可以在哪里重新创建它们以使它们持久存在?

Asp.net动态网格视图按钮

按钮可以使用命令字段或模板字段,下面是图像按钮的示例:

<asp:CommandField ShowEditButton="true" EditImageUrl="~/images/edit.png" ButtonType="Image" ItemStyle-Width="20px" HeaderStyle-Width="20px" AccessibleHeaderText="Edit">
  <HeaderStyle Width="20px" />
   <ItemStyle Width="20px" />
</asp:CommandField> 
Or 
<asp:TemplateField>
 <ItemTemplate>
  <asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit"
   ImageUrl="~/images/edit.png" ToolTip="Click to Edit></asp:ImageButton>
 </ItemTemplate>
</asp:TemplateField>

如果点击"点击我"按钮,请使用以下步骤绕过网格绑定

将OnRowBound函数代码更改为:

  protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItemIndex != -1)
            {
                Button button = new Button();
                button.ID = "gridview1row" + e.Row.RowIndex;
                button.UseSubmitBehavior = false;
                button.Text = "click me";
                button.Click += new EventHandler(Unnamed_Click);
                e.Row.Cells[1].Controls.Add(button);
            }
        }

在Grid View Load之前将以下检查添加到Page_Load

     protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if ( Request.Params["__EventTarget"] == null || !Request.Params["__EventTarget"].Contains("gridview1row"))
            {
                using (SqlConnection connection = new SqlConnection(GetConnectionString()))
                {
                    using (SqlCommand command =
                        new SqlCommand("SELECT TOP 100 * FROM dbo.TableName", connection))
                    {
                        DataSet ds = new DataSet();
                        SqlDataAdapter da = new SqlDataAdapter();
                        da.SelectCommand = command;
                        da.Fill(ds);
                        GridView1.DataSource = ds;
                        GridView1.DataBind();
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }