First your GridView has a property called DataKeyNames. Set this to the primary key of your data source. Now in your GridView create a ButtonField. Give it some text and specify the CommandName. CommandName can be any string but keep it simple.

Next create a RowCommand event for your GridView.

Next fill in the functionality for your command. In the event method you just have to test for which command was fired. Take a look at my example, it also shows how to get the GridView row index and the primary key so that I can delete the record from my sql table.
protected void gridServers_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName.ToLower().Equals("deleteserver")) {
int index = Convert.ToInt32(e.CommandArgument);
int ServerID = Convert.ToInt32(gridServers.DataKeys[index].Value);
clsServer server = new clsServer("mediadb");
server.ServerID = ServerID;
server.DeleteRecord();
gridServers.DataBind();
}
}
You can come up with other commands, just be creative.
12 comments:
But Dont we have to Set a value to the CommandArguement somewhere?
No, the GridView AUTOMATICALLY sets the commandargument property to the index of the row that had the command button clicked!
but in second row it givesan error "input string was in incorrect format.".
so how i can remove this error
Yeah, it is happening here too.
The int index will return only the valueof the first row primary key.
thanks for the tip just used it, and i feel like i gained a few experience points.
Rush, thanks for explanation of using GridView RowCommand. Very clearly explained.
Aha! DataKeyNames! That's what I was missing.
Thanks! :)
DataKeys & DataKeyNames array is empty!, I don't know why
Actually I dont want to use commandargument in rowcommand
Thank u sir
it give me answer to my questions
Ah! See what I was missing
int index = Convert.ToInt32(e.CommandArgument);
Thanks dear
Thanks this was exactly what I was after.
Post a Comment