2016-10-11 101 views
2

我有一個數據綁定的gridview:所有的行都根據ItemSource生成。我還在最後添加了一個包含按鈕的列。如何將當前itemSource中的字段綁定爲按鈕單擊事件的參數?如何通過按鈕點擊傳遞參數

下面是代碼示例:

WEBFORM

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="false" 
    ItemType="ServiceMonitoring.MyClass" 
    SelectMethod="GetMyClassItems" 
    CellPadding="4" 
    ShowFooter="true"> 
    <Columns> 
     <asp:BoundField DataField="MyProperty" HeaderText="ID" /> 
     <asp:TemplateField HeaderText="Action"> 
      <ItemTemplate> 
       <asp:Button runat="server" 
        CommandArgument='<%= MyClass.MyProperty %>' 
        CommandName="ThisBtnClick" 
        OnClick="Unnamed_Click" 
        Text="retraiter !" /> 
       <%--<button onclick="UpdateMyClassItems" runat="server" value="VALEUR">retraiter !</button>--%> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

代碼隱藏

public partial class WebForm1: System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) { } 

    public List<MyClass> GetMyClassItems() 
    { 
     var a = new MyClass() { MyProperty = 2 }; 
     return new List<MyClass>() { a }; 
    } 

    protected void Unnamed_Click(object sender, EventArgs e) 
    { 
     var arg = (sender as Button).CommandArgument; 
     string ID = arg.ToString(); 
    } 
} 

public class MyClass 
{ 
    public int MyProperty { get; set; } 
} 

命令的參數綁定不起作用。你能幫我嗎 ?

+0

@Aristos我現在有這個錯誤:CS0103:Le nom'MyClass'n'existe pas dans le contexte actuel('MyClass'這個名字不存在於當前的情況下)你能幫助我嗎? –

+0

錯誤英文請 – naveen

+0

@naveen當前上下文中不存在名稱'MyClass' –

回答

1

像這樣改變CommandArgument

CommandArgument='<%# Eval("MyProperty") %>' 

這樣做。你已經提及你的ItemType="ServiceMonitoring.MyClass"

+1

謝謝,它完美地工作。 –