2010-03-29 62 views
2

我想添加一列到包含按鈕控件的gridview。我使用ID(整數和主鍵)作爲Gridview的第一列。我想的是,當用戶點擊GridView中的任何給定行的按鈕,我希望能夠確定該點擊按鈕所屬ASP.NET C#在gridview記錄中顯示按鈕

VAM業

回答

4

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

1

要伴隨着@ 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>