Asp.net动态gridview按钮

时间:2014-07-21 11:32:37

标签: c# asp.net gridview

我有一个使用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);
        }

视觉上工作正常,但点击它时,它会进行回发并且更改会丢失。按钮不见了。

我可以在哪里重新创建它们以便它们持续存在?

2 个答案:

答案 0 :(得分:1)

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

<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>

答案 1 :(得分:0)

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

将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)
        {
        }

    }