I have a gridview with a databinding : all rows are generated depending on ItemSource. I have also add a column at the end containing a button. How to bind a field from current itemSource, as a parameter of button click event?
Here is code sample :
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>
Code-behind
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; }
}
Command argument binding doesn't work. Can you help me please ?
Change the CommandArgument like this.
CommandArgument='<%# Eval("MyProperty") %>'
that will do. You are already mentioning your ItemType="ServiceMonitoring.MyClass"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With