Some of the times you may need to use just one method for many controls like when you can to add a Button control to a GridView control for deleting a row manually (Because ASP.NET itself has such a thing).
in order to do this you cannot create a method for each row of GridView because of the following reasons:
- You don't know how much rows you may have.
- You have to spend a lot of times to do such a thing.
- You cannot (In some cases).
So lets see what should we do in order to create a these king of controls:
First of all create a GridView control and name it "GV_Items":
<asp:GridView runat="server" ID="GV_Items"></asp:GridView>
After that, add some columns to our GridView as following. Notice that I create a <TemplateField> as one of my columns and place a Button control in it:
<asp:GridView runat="server" ID="GV_Items" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Tel" HeaderText="Phone number" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="B_Delete" CommandName="Del" Text="Delete" CommandArgument='<%#Eval("PersonID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Our GridView control will be something like this:
As you can see, I set a CommandName (Del) and a CommandArgument (<%Eval("PersonID")%>) for my button. I preferred to get the value of my CommandArgument property from my database; So I used Eval keyword to that. (With Eval Keyword you can get a data from your database in Databound control such as GridView, Repeater, DataList and more. For more information you can check out: http://www.15seconds.com/issue/040630.htm)
Now it's time to write some code for this project. So lets go to code-behind mode and add a new method:
What we need is to create a method that delete a specified person from our database:
private void DeleteItem(int ItemId)
{
...
}
GridView Control has a event named RowCommand that enable you to manage your specified command names. I want to write some codes for this event so:
protected void GV_Items_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{
DeleteItem(Convert.ToInt32(e.CommandArgument));
}
}
I just used a if clause in order to check if my CommandName that sent to my GridView if "Del" (The CommandName that we set for our Button). If it's true, So delete the record by the DeleteItem method that we wrote. Our DeleteItem(int ItemId) requires a parameter to set which record of our database should be deleted. In order to set the parameter, I just used the parameter that we specified for my button (<%#Eval("PersonID")%>) than returns record's Id.
Now you know how to use the CommandName and CommandArgument properties of a control in order to develop better applications.