A Button or a link button in a GridView can
pass a value to the RowCommand
event in the code behind file using the CommandArgument
property.
Here the column is a link button column and will display the employee name, on clicking the link button the RowCommand event of the GridView is fired, and we are passing the EMPLOYEE_ID value to the row command property.
<asp:GridView
ID="grdEmployee"
runat="server"
OnRowCommand=" grdEmployee_RowCommand">
<Columns>
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:LinkButton
ID="lnkname"
runat="server"
Text='<%#Eval("EMPLOYEE_NAME") %>'
CommandArgument='<%#Eval("EMPLOYEE_ID") %>' CommandName="linkButton">
asp:LinkButton>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>
Here the column is a link button column and will display the employee name, on clicking the link button the RowCommand event of the GridView is fired, and we are passing the EMPLOYEE_ID value to the row command property.
protected void grdEmployee_RowCommand(object s, GridViewCommandEventArgs
e)
{
int intEmpId
= 0;
if
(e.CommandName == "linkButton")
{
intEmpId = Convert.ToInt32(e.CommandArgument);
}
}
This
is fine for passing a single value to the code behind event, what if we need to
pass more than one value to the code behind event, here is the code to acchieve
the same.
Here
we are passing the Employee_ID and Manager_ID values to the code behind event.
<asp:GridView
ID="grdEmployee"
runat="server"
OnRowCommand=" grdEmployee_RowCommand">
<Columns>
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:LinkButton
ID="lnkname"
runat="server"
Text='<%#Eval("EMPLOYEE_NAME") %>' CommandArgument='<%#Eval("EMPLOYEE_ID")
+ ","+Eval("MANAGER_ID") %>'
CommandName="linkButton">
CommandName="linkButton">
asp:LinkButton>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>
Here
is the code behind logic to receive the multiple values passed through the CommandArgument
protected void grdEmployee_RowCommand(object s, GridViewCommandEventArgs
e)
{
int intEmpId = 0;
int intMgrId = 0;
int intMgrId = 0;
if
(e.CommandName == "linkButton")
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
intEmpId = Convert.ToInt32(commandArgs[0]);
intMgrId = Convert.ToInt32(commandArgs[1]);
}
}
}
That’s
it we have now passed multiple values using the CommandArgument property
and received the same in the RowCommand event of the code behind file.
No comments:
Post a Comment