Tuesday, November 21, 2006

Using GridView RowCommand

I haven't used this in 6 months and had to lookup how to do it. For some reason the built-in GridView "delete" feature does not work for me (have tried it on multiple setups). Fortunately it is not hard to replicate.

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:

Anonymous said...

But Dont we have to Set a value to the CommandArguement somewhere?

Anonymous said...

No, the GridView AUTOMATICALLY sets the commandargument property to the index of the row that had the command button clicked!

Anonymous said...

but in second row it givesan error "input string was in incorrect format.".
so how i can remove this error

Anonymous said...

Yeah, it is happening here too.
The int index will return only the valueof the first row primary key.

aApe said...

thanks for the tip just used it, and i feel like i gained a few experience points.

Anonymous said...

Rush, thanks for explanation of using GridView RowCommand. Very clearly explained.

Andy said...

Aha! DataKeyNames! That's what I was missing.
Thanks! :)

Anonymous said...

DataKeys & DataKeyNames array is empty!, I don't know why

Anonymous said...

Actually I dont want to use commandargument in rowcommand

Bharat Bhushan said...

Thank u sir
it give me answer to my questions

Ope Nigeria said...

Ah! See what I was missing
int index = Convert.ToInt32(e.CommandArgument);

Thanks dear

Anonymous said...

Thanks this was exactly what I was after.