繁体   English   中英

Asp.net动态gridview按钮

[英]Asp.net dynamic gridview buttons

我有一个用SQL数据填充的gridview,我想将按钮/链接按钮动态添加到其列中。

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: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);
            }
        }

在网格视图加载之前将以下检查添加到您的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)
        {
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM