Deleting Gridview Row

Hello all,

I would like to know how to delete a gridview row on button click. I' m not using the auto generated delete button because of a requirement.

Thanks for the help.
Who is Participating?
Hi, I assume you want to delete the underlying record in a gridview row from the database.
Let me know if its other way round.

Ok , so you have a linkbutton in grid, assign its commandargument to the dataitemindex i.e. it'll store
the row. syntax would be: CommandArgument=<%# Container.DataItemIndex %> in the button markup.

Also, I assume that the primary key or identifier is kept in datakey in gridview.

so on click of a linkbutton, you fetch its command argument
command argument gives you the rowid where button is clicked
using rowid, you fetch that row's datakey of the particular value you want to identify it in database
then delete it from database by passing that key in your deletefunction of database.

Let me know if its confusing you or you are stuck at any particular point.
Happy Coding!
Oops forgot to add that 'You have to re-bind the grid after you delete the record in order to reflect the changes in web form'
AvinashKNAuthor Commented:
Thanks for the quick reply.

I have created a method to remove the row. What I'm finding difficult is to get the value of the row.

For example...

I'm using the following code to change the color of a particular account number..

if (e.Row.RowType == DataControlRowType.DataRow)
            string strAccountNumber = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Account No"));
            if (strAccountNumber == "7000512518001")

                e.Row.BackColor = System.Drawing.Color.Red;

I would like to know how to select the row based on the account number like I'm doing there.
Hi, like I said, in the row, you have to set your button's command argument to container.dataitemindex.   Set your "Account No" as datakey value for your gridview, you can even set it from the front end property box.  

Then access current row's datakey value to get your account no as I have already mentioned in the example.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.