簡體   English   中英

ASP.NET C#在gridview記錄中顯示按鈕

[英]ASP.NET C# Show buttons in gridview records

我想向包含按鈕控件的gridview添加一列。 我正在使用ID(整數和主鍵)作為Gridview的第一列。 我想要的是,當用戶單擊gridview的任何給定行上的按鈕時,我希望能夠確定所單擊的按鈕所屬的行的ID。

葉偉業

在網格視圖的模板中,將按鈕的CommandArgument屬性綁定到該行的ID。 然后在按鈕單擊事件上,從事件args中檢查commandArgument屬性。 這會給你ID

為了配合@Midhat的答案,下面是一些示例代碼:

后面的代碼:

public partial class _Default : System.Web.UI.Page
{
  List<object> TestBindingList;

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
        TestBindingList = new List<object>();
        TestBindingList.Add(new { id = 1, name = "Test Name 1" });
        TestBindingList.Add(new { id = 2, name = "Test Name 2" });
        TestBindingList.Add(new { id = 3, name = "Test Name 3" });

        this.GridView1.DataSource = TestBindingList;
        this.GridView1.DataBind();
    }

  }

  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  {         
    if (e.CommandName == "Select")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        this.Label1.Text = this.GridView1.DataKeys[index]["id"].ToString();
    }
  }
}

標記:

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"  
    onrowcommand="GridView1_RowCommand" DataKeyNames="id">
    <Columns>
        <asp:TemplateField HeaderText="ButtonColumn">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" 
                    CommandName="Select" Text="ClickForID"
                     CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>


</form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM