我有一个带数据绑定的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 :(得分:1)
像这样更改CommandArgument
。
CommandArgument='<%# Eval("MyProperty") %>'
会这样做。您已经提到了ItemType="ServiceMonitoring.MyClass"