deleting a gridview row > deleting a record by id?

I know this is supposed to be really simple but I'm stumped, despite all my reading:

I've got a gridview full of 'Categories' pulled rom my SQL db; each row has a (hidden) 'category_id' column.

My delete button should ensure that the appropriate record is marked for deletion by category_id.

I understand that somehow the point of a datagrid is that it is bound to my datatable - but how do I leverage that so that deleting a grid row (which might be row index 1) finds and deletes the correct record (which might be category_id 3125)? (All I need to do is flag the row as deleted, then call my SQLAdapter.Update, correct?)

My gut tells me I'm overthinking it - that I don't need to explicitly hunt down the id in the row I chose, that the gridview will automagically know which one. But how?

 

<asp:GridView id="grdCategories" runat="server" AutoGenerateColumns="False" onrowcommand="grdCategories_RowCommand" OnRowDataBound="grdCategories_RowDataBound">
    <Columns>
        <asp:BoundField DataField=">
        <asp:BoundField DataField="english_text" HeaderText="English" />
        <asp:TemplateField HeaderText="Delete Category">
            <ItemTemplate>
                <asp:Button ID="lnkDeleteCat" CommandArgument='<%# Eval("category_id") %>' CommandName="Delete" Text="Delete" runat="server" OnClientClick="return confirm('Delete this category? All questions in this category will be moved to Archive.');" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
  
       protected void grdCategories_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                int category_id = Convert.ToInt32(e.CommandArgument);
                DataRow rowToDelete = FindRowWithID(dsCats.Tables[0],category_id);
                ??dsCats.Tables[0].Rows(???).Delete();
            }

protected DataRow FindRowWithID(DataTable dt, int id)
{
    DataRow foundRow = dt.Rows.Find("primaryKeyValue");
    if (foundRow != null)
    {
        return foundRow;
    }
    else
    {
        return null;
    }
}

 
0
DaveC426913
12/5/2008 9:39:34 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies
2180 Views

Similar Articles

[PageSpeed] 27

Set the following property (on the gridview) to the primary key of your datasource. 

DataKeyNames


C# <---> VB.Net Translator
0
MetalAsp
12/5/2008 10:09:12 PM

Thanks.

Of course, my attempted code is still a mess. I've got to get that right too. I'll look up DataKeyNames.

 [Update:] I'm just not getting it. I must be over thinking it. I simply want to have my DELETE button delete that row from my dataset.

Every article I read says that the way to delete a datarow from a dataset is trivial: myDataTable.myDataRow.Delete(n); but it doesn't tell you how to get n. And it doesn't tell you WHERE to put that: in the RowCommand, the RowDeleting or somewhere else!

 

 

0
DaveC426913
12/8/2008 3:08:39 PM

Hi DaveC426913,

Try this:

if (e.CommandName.Equals("Delete"))
{
    string category_id = e.CommandArgument;
    for (int i = 0; i < dsCats.Tables[0].Rows.Count; i++)
    {
        if (dsCats.Tables[0].Rows[i]["category_id"].ToString() == category_id)
        {
            dsCats.Tables[0].Rows[i].Delete();
            dsCats.Tables[0].AcceptChanges();
        }
    }
}

Thanks,


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Qin
12/10/2008 7:39:32 AM

If you are trying to use one of the built in commands it probably better to use the OnDeleting event, but the code does translate well from what Qin Dian Tang, suggests.


David Fowler
SDE, ASP.NET Team, Microsoft
0
davidfowl
12/10/2008 7:50:40 AM

Thanks, that's got it working. (One change: e.CommandArgument.ToString() )

OK,  dsCats was null when I went to delete a row, so I've added dsCats = (DataSet)Session["FAQCategories"];

It's working, except that the row isn't being deleted from the db. I checked: before the Delete and there were 5 rows in the dataset, after the Delete there are only 4 rows. So it's doing its job correctly, but when it's getting to the database, it's not deleting it. No error. This may be one of those situations I read about where the database doesn't know that there's a record to delete.

 

        protected void grdCategories_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            dsCats = (DataSet)Session["FAQCategories"];
            if (e.CommandName.Equals("Delete"))
            {
                string category_id = e.CommandArgument.ToString();
                for (int i = 0; i < dsCats.Tables[0].Rows.Count; i++)
                {
                    if (dsCats.Tables[0].Rows[i]["category_id"].ToString() == category_id)
                    {
                        dsCats.Tables[0].Rows[i].Delete();
                        dsCats.Tables[0].AcceptChanges();
                    }

                }
                DBLayer.updateCategories(dsCats);
                Server.Transfer("manage_categories.aspx");
            }
        }

        public static int updateCategories(DataSet ds)
        {
            string sqlstr = "select * from FAQCategories ORDER BY position_num";

            SqlConnection conn = new SqlConnection(_cs);
            try
            {
                SqlDataAdapter sqlad = new SqlDataAdapter(sqlstr, conn);
                new SqlCommandBuilder(sqlad);
                sqlad.Update(ds, "FAQCategories");

            }
            catch (Exception)
            {
                return 0;
            }
            finally
            {
                conn.Close();
            }
            return 1;
        }
  
0
DaveC426913
12/11/2008 5:32:32 PM

Hi DaveC426913,

Try to use DataTable name to do deleting, make sure you have set the DataTable name "FAQCategories" in Session["FAQCategories"]:

for (int i = 0; i < dsCats.Tables["FAQCategories"].Rows.Count; i++)
                {
                    if (dsCats.Tables["FAQCategories"].Rows[i]["category_id"].ToString() == category_id)
                    {
                        dsCats.Tables["FAQCategories"].Rows[i].Delete();
                        dsCats.Tables["FAQCategories"].AcceptChanges();
                    }
                }

And open SqlConnection before updating:

SqlConnection conn = new SqlConnection(_cs);
conn.Open();

Here is a good example of doing updating through SqlDataAdapter.Update(): http://support.microsoft.com/kb/308055

Thanks,


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Qin
12/12/2008 2:22:05 AM
Reply:

Similar Artilces:

How to delete controls in GridView when the delete button in a row is clicked
Hi,   I am having issues with my gridview.....i added 2 dropdown and 2 compare validators....whenever i delete a row though......the dropdown and compare validators are becoming null........thus when i click a button, it is still validating.............anyway to delete this when i click the delete button or even handle?   Please help.  ...

delete row or delete all in Gridview?
Hi there, I have a Gridview that bind the data from the .mdb  and I want to have 2 delete buttions, one is delete a row and the other one is delete all from the database.  How do I do it in code behind in c#?  thanks a lot row delete  (temp call rowDel) all delete (temp call allDel) with rowDel: i think you should bound one column in gridview  (or datagrid)<asp:ButtonColumn... and bout allDel: i think you should use a button distinct with gridview.Becoz your required is not complex , when allDel be push you don't care...

Adding data to gridview from two textboxes and then deleting them by delete button in each gridview row.
Hi, my app has 2 textboxes if i enter data and click add button they shud be added to gridview with 2 columns ex: custid from txtbox1 ... and custname frm txtbox2 added to gridview   with columns custid and custname then    foreach row a delete button shud appear in gridview and on clicking it shud delete the row can any one send me code for dis   thanks in advance Hi, In your Button Click Event write this code. DataControlField dCusId; DataControlField dCustName; dCusId.HeaderText = textbox1.text; dCustName.HeaderText = textbox2.text Gridv...

Gridview Delete not Deleting
I am trying to use a command button to delete a row from a gridview. When I click the command button though, the page posts but my record is still there... no errors, just nothing seems to happen. Below is what I think is the relevant code, let me know if you need to see anything else.  I'm kinda new to working with gridview objects, it would be nice if I could see what SQL command is acctually ran... maybe there are other things I can check too, I'm just not sure how.   <asp:GridView ID="GridView1" runat="server" AllowSorting="True"&nbs...

Deleting records and selecting the records after the delete
iam trying to delete a record from the database using ADO.NET which works fine. After i delete a record i want to refresh the page by selecting the remaining records in the database. What shud be done to achieve this? i have tried creating a new data adapter and filling the dataset by using the selectcommand but i am still able to see the deleted record. what am i doing wrong? Thanks If you are using SQL Server these steps can be performed using a stored procedure. How to use a stored procedure and why cant i make it work by using individual queries? what does the stored procedure ...

Delete a Row From A GridView Control
Well it is not just an ordinary delete. I have a Gridview which I populated manually. Then I need to delete a row which will be selected using a checkbox inside the gridview. I cant seem to find the way to just remove the specific row. I have already taken the rowIndex, but Gridview doesnt seem to allow me to delete a row unless I remove from a dataset or so. Anyhelp would be appreciated. Thanks - Mike use the property "DataKeyName" of the GridView. get the index and delete/remove the perticular row which you got through datakeyname property. and again bind your GridView. Thanx, [K...

How to delete row from GridView control
Hello,  I am working on an ASP.NET 2.0 app, and I am trying to wire up a "Delete" button to a gridview control on a form. Here is the code for the ASP :  <asp:GridView ID="gvInConditions" runat="server" AutoGenerateColumns="true" OnRowDeleting="gvInConditions_RowDeleting" DataKeyNames="Condition_ID" >         <Columns>                <asp:CommandField ButtonType="Button" SelectText=&...

Gridview Delete link not deleting record with 2 parameters
I have a DeleteApprovedSoftware method that expects two parameters in order to delete a record: SoftwareID (int) and Version (string). I have provided my delete method in the objectdatasource setup and select Enable Deleting. When I click on the delete link it is not deleting the record. I have posted my code below. Is it now obtaining the SoftwareID and Version ID values from the Gridview in order to pass it to the DeleteApprovedSoftware method?    "gvwCISSoftware" runat="server" AutoGenerateColumns="False" DataSourceID="CISSoftwareO...

Having a delete confirmation box appear when a record is deleted from a gridview.
Hello i have a page with a gridview component that manipluates data from a SQL Server database. I have enabled deleting on the gridview, which automatically has coded my delete function. however i would like when the user clicks delete, a dialog box appear confirming if they wish to delete the record and presented with the options ok or cancel. Is there a way of implementing this? Any help would be appreciated. Thanks, James In GridView Tasks, select Edit Columns... Select the Delete command and then click the link "Convert this field into a template" In the asp source code, ...

Delete (Hide) Row from Gridview without deleting from DataBase
I am populating some data in a GridView.I added a column with a checkbox.Now I want to generate a sort of print-preview...When Ich check some buttons and hit my printpriview button. I only want these (selected rows displayed).How can I do this?The checkbox thing is already working What I basically need is something to delete data temporaly from a GridView (not Database).I tryed GridViewRow.Dispose() which worked but then the paging was still implementet and the user sees still all pages =(I have tryed GridViewRow.Enabled = false which only turned the colors =(I have used GridViewRow.Visible ...

Error with Gridview when i delete the row that have only one row in gridview
 Dear all, i develop with asp.net 2005 and use gridview and set enable deleteing =true. I can delete record in gridview properly but when gridveiw has only one row and then i'm clike delete button , the error occurs :   Server Error in '/it' Application. Specified argument was out of the range of valid values.Parameter name: value Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentOutOfRangeExce...

Deletes are not being deleted.
Using ASA 7.03 I am having a problem in deleting field service orders that have been completed. Just getting started with sync so I am probably making a dumb mistake or just leaving out a step. The download_delete_cursor script is: Select ordernumber from ServiceOrderEntryMaster where Tech = ? and Order_Complete = 'Y' This based on the verbose reply from the MobiLink Synchronization server is picking the correct work order ( number 326 ) and showing a Delete Row line in the log. But the work order is not being deleted on the remote side. What could I be doing wron...

Gridview
I have a gridview and Iam using the 'built in-delete-button' : <asp:CommandField ShowDeleteButton="True" /> When a user press the deletebutton, I want to grab the ID of that post and add that ID to a parameter in a sqldatasource. I have the DataKeyNames="ID" of the Gridview and I tried with the code below, But I think this is just working if I use ShowSelectButton="True" and not when using ShowDeleteButton="True"... Is that correct? I want to do something like this with the SqlDataSource: <SelectParameters> <asp:ControlParameter ControlID="GridView1" Name="ID" Proper...

Help on deleting a row in Gridview control
Hi, I need to find out how to delete a row in the GridView control.  I have the following delete control in my GridView:<CODE><asp:TemplateField ItemStyle-HorizontalAlign=center ItemStyle-VerticalAlign="top"><ItemTemplate><asp:ImageButton ID=ibDelete runat=server ImageUrl="~/Images/delete.gif" CommandName="Delete"/></ItemTemplate> </asp:TemplateField></CODE> What events do I use and how do I get them to fire?  I just started using Gridviews.thanks. Hey,That should all you need to delete a row; a cli...

Web resources about - deleting a gridview row > deleting a record by id? - asp.net.presentation-controls

Deleting Online Predators Act of 2006 - Wikipedia, the free encyclopedia
( DOPA ) is a bill ( H.R. 5319 ) brought before the United States House of Representatives on May 9, 2006 by Republican Pennsylvania Representative ...

Facebook Deleting Inflammatory Content In India
Facebook has been complying with a request by the government of India and removing “inflammatory and hateful content” that has caused tens of ...

Deleting your Facebook page is foolish
... brag, trailing closely behind that fantastically annoying “I don’t even have a TV , never mind watch the drivel!” Let’s lay it out: deleting ...

AdWords Campaign Experiments: Applying or deleting your experimental changes - YouTube
To improve your AdWords experience, we're testing a new tool that helps you optimize your account. AdWords Campaign Experiments, or ACE, does ...

Deleting abusive online content a 'near impossible' task
POSTING offensive, harassing, intimidating or defamatory content online takes mere seconds, but getting it removed can take what feels like a ...

Paleo advocate Pete Evans accused of deleting critical posts on Facebook
Is Paleo Pete Evans is open to dietary debate? Some say he's not.

Microsoft on the threshold of deleting 'appalling' Windows 8 software
MICROSOFT plans to cut its losses on Windows 8, the latest version of the software that runs the majority of the world's computers, jettisoning ...

How to get iOS 8 without deleting everything on your phone
If you've tried downloading iOS 8, or know anyone who has already done so, you're probably familiar with the biggest complaint: The download ...

Dalton McGuinty staffers broke law by deleting gas plant emails
Senior staff members in the offices of both the Ontario energy minister and former premier Dalton McGuinty intentionally deleted emails about ...

Jason Kenney under fire for praising ‘perfect, unaccented English’, deleting tweet
Canada's Minister for Multiculturalism, Jason Kenney, caused an upset Monday after praising an 11-year-old Iraqi refugee who "already speaks ...

Resources last updated: 12/6/2015 10:22:55 PM