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