Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. Removing items from a datagrid???

Removing items from a datagrid???

Scheduled Pinned Locked Moved ASP.NET
csshelptutorialquestion
24 Posts 2 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Ironsmith1977
    wrote on last edited by
    #1

    I'm making my first shopping cart and so far I have the datagrid populating perfectly, I have check box's in one column so the user can select which items, if any, that they can remove. However, I'm lost on how to code in the events to actually remove these items from the grid. I used a session state variable to collect the items the user selects, then I put those items into a DataTable, then I bound that DataTable to the datagrid. So when a user wants to remove an item(s) from the shopping cart, it also has to remove them from the DataTable. Because I'm sure that I'll have to rebuild the DataGrid after the user removes the items. And so, if that data is still in the DataTable, then it'll be pointless as it'll show up back in the DataGrid. This is what I have right now, this code just clears the whole grid private void btnRemove_Click(object sender, System.EventArgs e) { DataTable dt = (DataTable)Session["Items"]; dt.Rows.Clear(); Session["Items"] = dt; PurchaseDataGrid.DataSource = dt; PurchaseDataGrid.DataBind(); } I'm not even sure if this is close to correct, really I'm just picking at straws right now. I really hope that someone out there can help me. Many thanks in advance. Take care Ironsmith

    M 1 Reply Last reply
    0
    • I Ironsmith1977

      I'm making my first shopping cart and so far I have the datagrid populating perfectly, I have check box's in one column so the user can select which items, if any, that they can remove. However, I'm lost on how to code in the events to actually remove these items from the grid. I used a session state variable to collect the items the user selects, then I put those items into a DataTable, then I bound that DataTable to the datagrid. So when a user wants to remove an item(s) from the shopping cart, it also has to remove them from the DataTable. Because I'm sure that I'll have to rebuild the DataGrid after the user removes the items. And so, if that data is still in the DataTable, then it'll be pointless as it'll show up back in the DataGrid. This is what I have right now, this code just clears the whole grid private void btnRemove_Click(object sender, System.EventArgs e) { DataTable dt = (DataTable)Session["Items"]; dt.Rows.Clear(); Session["Items"] = dt; PurchaseDataGrid.DataSource = dt; PurchaseDataGrid.DataBind(); } I'm not even sure if this is close to correct, really I'm just picking at straws right now. I really hope that someone out there can help me. Many thanks in advance. Take care Ironsmith

      M Offline
      M Offline
      minhpc_bk
      wrote on last edited by
      #2

      Hi Ironsmith, In the btnRemove_Click event handler, you basically need to get through all items of the grid and remove the rows which are selected by checking the row's checkbox. The sample code is something like this:

      private void btnRemove_Click(object sender, System.EventArgs e)
      {
      DataTable dt = (DataTable)Session["Items"];
      foreach(DataGridItem item in PurchaseDataGrid.Items)
      {
      //Here, I assume the checkbox is placed in the column 1.
      //You can also use the FindControl method to get a reference to the checkbox.
      CheckBox chkBox = item.Cells[0].Controls[1] as CheckBox;
      if(chkBox.Checked)
      {
      //Put your code here to remove the selected item from the data source.
      //...
      }
      }

           //Save the datasource in Session
           Session\["Items"\] = dt; 
                               
           //Rebind the updated datasource to the datagrid
           PurchaseDataGrid.DataSource = dt;
           PurchaseDataGrid.DataBind(); 
      

      }

      If the Delete button is placed in the datagrid, you may also need to create an event handler for the ItemCommand event of the datagrid and put the code to do your business according to the CommandName. For more information, you can see Allowing Users to Delete Items in a DataGrid Web Server Control[^] DataGrid.ItemCommand Event[^] Deleting a Row from a Table[^]

      I 1 Reply Last reply
      0
      • M minhpc_bk

        Hi Ironsmith, In the btnRemove_Click event handler, you basically need to get through all items of the grid and remove the rows which are selected by checking the row's checkbox. The sample code is something like this:

        private void btnRemove_Click(object sender, System.EventArgs e)
        {
        DataTable dt = (DataTable)Session["Items"];
        foreach(DataGridItem item in PurchaseDataGrid.Items)
        {
        //Here, I assume the checkbox is placed in the column 1.
        //You can also use the FindControl method to get a reference to the checkbox.
        CheckBox chkBox = item.Cells[0].Controls[1] as CheckBox;
        if(chkBox.Checked)
        {
        //Put your code here to remove the selected item from the data source.
        //...
        }
        }

             //Save the datasource in Session
             Session\["Items"\] = dt; 
                                 
             //Rebind the updated datasource to the datagrid
             PurchaseDataGrid.DataSource = dt;
             PurchaseDataGrid.DataBind(); 
        

        }

        If the Delete button is placed in the datagrid, you may also need to create an event handler for the ItemCommand event of the datagrid and put the code to do your business according to the CommandName. For more information, you can see Allowing Users to Delete Items in a DataGrid Web Server Control[^] DataGrid.ItemCommand Event[^] Deleting a Row from a Table[^]

        I Offline
        I Offline
        Ironsmith1977
        wrote on last edited by
        #3

        Hello, I must be missing something because I keep getting a compile error. I put in the code sample you provided, but the code to delete the row from the data source is not working. Your right, I do have the checkboxes in the first column. I didn't use the properties builder, I added them in HTML view and gave it the id chkRemove. I checkout out both links you provided, and while I think that the msdn is great, from time to time, I just can't make any sense out of it. lol. Here is what I have: private void btnRemove_Click(object sender, System.EventArgs e) { DataTable dt = (DataTable)Session["Items"]; foreach(DataGridItem item in PurchaseDataGrid.Items) { CheckBox chkRemove = item.Cells[0].Controls[1] as CheckBox; if (chkRemove.Checked) { dt.Rows[0].Delete(); } } Session["Items"] = dt; PurchaseDataGrid.DataSource = dt; PurchaseDataGrid.DataBind(); This only removes the first row. I gather because I specified "dt.Rows[0].Delete();" Therefore, it deletes row [0], however, I need it to delete any row that is checked. Take care and thanks for the help! Ironsmith

        M 1 Reply Last reply
        0
        • I Ironsmith1977

          Hello, I must be missing something because I keep getting a compile error. I put in the code sample you provided, but the code to delete the row from the data source is not working. Your right, I do have the checkboxes in the first column. I didn't use the properties builder, I added them in HTML view and gave it the id chkRemove. I checkout out both links you provided, and while I think that the msdn is great, from time to time, I just can't make any sense out of it. lol. Here is what I have: private void btnRemove_Click(object sender, System.EventArgs e) { DataTable dt = (DataTable)Session["Items"]; foreach(DataGridItem item in PurchaseDataGrid.Items) { CheckBox chkRemove = item.Cells[0].Controls[1] as CheckBox; if (chkRemove.Checked) { dt.Rows[0].Delete(); } } Session["Items"] = dt; PurchaseDataGrid.DataSource = dt; PurchaseDataGrid.DataBind(); This only removes the first row. I gather because I specified "dt.Rows[0].Delete();" Therefore, it deletes row [0], however, I need it to delete any row that is checked. Take care and thanks for the help! Ironsmith

          M Offline
          M Offline
          minhpc_bk
          wrote on last edited by
          #4

          What does the error say? I take it the compile error is not coming from your sample code if you include all assemblies properly as I don't see anything special in there. and while I think that the msdn is great, from time to time, I just can't make any sense out of it. lol MSDN is your good friend but you may need a little more time. :)

          I 1 Reply Last reply
          0
          • M minhpc_bk

            What does the error say? I take it the compile error is not coming from your sample code if you include all assemblies properly as I don't see anything special in there. and while I think that the msdn is great, from time to time, I just can't make any sense out of it. lol MSDN is your good friend but you may need a little more time. :)

            I Offline
            I Offline
            Ironsmith1977
            wrote on last edited by
            #5

            I'm not getting the compile error anymore, however, it will only delete the one row. I need to know how to delete the rows that are selected. The ASP.NET books that I have don't have anything on DataTables, as unbelievable as that sounds, and the info I'm finding online is very limited. I know that I'm specifying row[0] and that's most likely why I'm only deleting one row, the first row. So how would I change that to make it so I can delete anything that is selected? Ironsmith

            M 1 Reply Last reply
            0
            • I Ironsmith1977

              I'm not getting the compile error anymore, however, it will only delete the one row. I need to know how to delete the rows that are selected. The ASP.NET books that I have don't have anything on DataTables, as unbelievable as that sounds, and the info I'm finding online is very limited. I know that I'm specifying row[0] and that's most likely why I'm only deleting one row, the first row. So how would I change that to make it so I can delete anything that is selected? Ironsmith

              M Offline
              M Offline
              minhpc_bk
              wrote on last edited by
              #6

              Ok, the problem now is how to specify the selected rows to delete. There are a lot of ways to select rows from table. Here is just one of them, I am using the DataKey property of the datagrid to keep the id of each row, then in the event handler I can get the row based on this value, the sample code looks something like this:

              private void btnRemove_Click(object sender, System.EventArgs e)
              {
              DataTable dt = (DataTable)Session["Items"];
              int index = 0;
              foreach(DataGridItem item in DataGrid1.Items)
              {
              CheckBox chkRemove = item.Cells[0].Controls[1] as CheckBox;
              if (chkRemove.Checked)
              {
              string id = DataGrid1.DataKeys[index] as string;
              DataRow[] rows = dt.Select("ItemID='"+ id + "'");
              rows[0].Delete();//I assume that returns one row.

                }
                index++;
              

              }

              Session["Items"] = dt;
              DataGrid1.DataSource = dt;
              DataGrid1.DataBind();
              }

              You can also use the following code to delete a row:

              ....
              DataRow row = dt.Rows.Find(ItemsGrid.DataKeys[index]);
              if(row != null)
              {
              dt.Rows.Remove(row);
              }
              ....

              For more information, see BaseDataList.DataKeys Property[^] Creating and Using DataTables[^]

              I 1 Reply Last reply
              0
              • M minhpc_bk

                Ok, the problem now is how to specify the selected rows to delete. There are a lot of ways to select rows from table. Here is just one of them, I am using the DataKey property of the datagrid to keep the id of each row, then in the event handler I can get the row based on this value, the sample code looks something like this:

                private void btnRemove_Click(object sender, System.EventArgs e)
                {
                DataTable dt = (DataTable)Session["Items"];
                int index = 0;
                foreach(DataGridItem item in DataGrid1.Items)
                {
                CheckBox chkRemove = item.Cells[0].Controls[1] as CheckBox;
                if (chkRemove.Checked)
                {
                string id = DataGrid1.DataKeys[index] as string;
                DataRow[] rows = dt.Select("ItemID='"+ id + "'");
                rows[0].Delete();//I assume that returns one row.

                  }
                  index++;
                

                }

                Session["Items"] = dt;
                DataGrid1.DataSource = dt;
                DataGrid1.DataBind();
                }

                You can also use the following code to delete a row:

                ....
                DataRow row = dt.Rows.Find(ItemsGrid.DataKeys[index]);
                if(row != null)
                {
                dt.Rows.Remove(row);
                }
                ....

                For more information, see BaseDataList.DataKeys Property[^] Creating and Using DataTables[^]

                I Offline
                I Offline
                Ironsmith1977
                wrote on last edited by
                #7

                I keep getting an exception error at the [index] saying its out of range, cannot accept negative values and must be below maximum value. I can't figure out what this means. I stepped through the code and the index value while stepping through is at 1. Any idea's? Take care, and you've been a huge help to me. Ironsmith

                M 1 Reply Last reply
                0
                • I Ironsmith1977

                  I keep getting an exception error at the [index] saying its out of range, cannot accept negative values and must be below maximum value. I can't figure out what this means. I stepped through the code and the index value while stepping through is at 1. Any idea's? Take care, and you've been a huge help to me. Ironsmith

                  M Offline
                  M Offline
                  minhpc_bk
                  wrote on last edited by
                  #8

                  Is this line causing the error?

                  string id = DataGrid1.DataKeys[index] as string;

                  Do you set the DataKeyField property in the page or in code? For example:

                  DataGrid1.DataKeyField = "ItemID";

                  "ItemID" is one of the data table columns. If you don't set this property, then the ArgumentOutOfRangeException will happen when you are trying to run the above code.

                  I 1 Reply Last reply
                  0
                  • M minhpc_bk

                    Is this line causing the error?

                    string id = DataGrid1.DataKeys[index] as string;

                    Do you set the DataKeyField property in the page or in code? For example:

                    DataGrid1.DataKeyField = "ItemID";

                    "ItemID" is one of the data table columns. If you don't set this property, then the ArgumentOutOfRangeException will happen when you are trying to run the above code.

                    I Offline
                    I Offline
                    Ironsmith1977
                    wrote on last edited by
                    #9

                    I set the DataKeyFields in code actually, until run time, the DataGrid displays nothing with no column headers or anything. Only after Items are selected will the grid populate. The only static field in the grid is the "Remove" column, which is holding checkboxes. Take care Ironsmith

                    M 1 Reply Last reply
                    0
                    • I Ironsmith1977

                      I set the DataKeyFields in code actually, until run time, the DataGrid displays nothing with no column headers or anything. Only after Items are selected will the grid populate. The only static field in the grid is the "Remove" column, which is holding checkboxes. Take care Ironsmith

                      M Offline
                      M Offline
                      minhpc_bk
                      wrote on last edited by
                      #10

                      Hi Ironsmith, I'm back, is it working now?

                      I 1 Reply Last reply
                      0
                      • M minhpc_bk

                        Hi Ironsmith, I'm back, is it working now?

                        I Offline
                        I Offline
                        Ironsmith1977
                        wrote on last edited by
                        #11

                        Hello, No its not. I think from what others have told me, it's because I don't have a unique identifier column. None of the columns in my table are unique, I don't have a "ItemID" column or any other numbering system in the DataGrid. Therefore, trying to specify what row to delete, has been the main problem. If you check out my first post in this thread, I posted my code. It hasn't changed much since I posted that. Take care Ironsmith

                        M 1 Reply Last reply
                        0
                        • I Ironsmith1977

                          Hello, No its not. I think from what others have told me, it's because I don't have a unique identifier column. None of the columns in my table are unique, I don't have a "ItemID" column or any other numbering system in the DataGrid. Therefore, trying to specify what row to delete, has been the main problem. If you check out my first post in this thread, I posted my code. It hasn't changed much since I posted that. Take care Ironsmith

                          M Offline
                          M Offline
                          minhpc_bk
                          wrote on last edited by
                          #12

                          Well in this case, IMO there are a few options here: + You have to re-design the table schema in order that there is a way to select a specific row in a table, I mean it should have a unique column. + You can select the row by its index. I mean if you select the second row in the grid to delete, then at the server side you can delete the second row in the data table. However, this is not recommended as if you use paging, the index might not be correct when you are in another page orher than 1.

                          I 1 Reply Last reply
                          0
                          • M minhpc_bk

                            Well in this case, IMO there are a few options here: + You have to re-design the table schema in order that there is a way to select a specific row in a table, I mean it should have a unique column. + You can select the row by its index. I mean if you select the second row in the grid to delete, then at the server side you can delete the second row in the data table. However, this is not recommended as if you use paging, the index might not be correct when you are in another page orher than 1.

                            I Offline
                            I Offline
                            Ironsmith1977
                            wrote on last edited by
                            #13

                            Is there a way to create a column that AutoIncrements? Or is there a way that I can hard code in row numbers? However, since I'll never know exactly how many rows there will be in the DataGrid, that's most likely not a good idea. Well, unless I can AutoIncrement a column somehow, I guess I'll just have to leave it as is, it deletes the first row. lol. Horrible, but I'm running out of time. Take care Ironsmith

                            M 1 Reply Last reply
                            0
                            • I Ironsmith1977

                              Is there a way to create a column that AutoIncrements? Or is there a way that I can hard code in row numbers? However, since I'll never know exactly how many rows there will be in the DataGrid, that's most likely not a good idea. Well, unless I can AutoIncrement a column somehow, I guess I'll just have to leave it as is, it deletes the first row. lol. Horrible, but I'm running out of time. Take care Ironsmith

                              M Offline
                              M Offline
                              minhpc_bk
                              wrote on last edited by
                              #14

                              It's very simple to create an autoincrement column, take a quick look at the sample code below:

                              DataColumn itemIDCol = dataTable.Columns.Add("ItemID", typeof(Int32));
                              itemIDCol.AutoIncrement = true;
                              itemIDCol.AutoIncrementSeed = 0;
                              itemIDCol.AutoIncrementStep = 1;

                              This column starts with a value of 0 and adds incrementally in steps of 1. For more information, see Creating AutoIncrement Columns[^] DataColumn Class[^]

                              I 1 Reply Last reply
                              0
                              • M minhpc_bk

                                It's very simple to create an autoincrement column, take a quick look at the sample code below:

                                DataColumn itemIDCol = dataTable.Columns.Add("ItemID", typeof(Int32));
                                itemIDCol.AutoIncrement = true;
                                itemIDCol.AutoIncrementSeed = 0;
                                itemIDCol.AutoIncrementStep = 1;

                                This column starts with a value of 0 and adds incrementally in steps of 1. For more information, see Creating AutoIncrement Columns[^] DataColumn Class[^]

                                I Offline
                                I Offline
                                Ironsmith1977
                                wrote on last edited by
                                #15

                                Oh that is awesome, I just did it and it works great. Good to know that I'm not completely screwed! Thank you very much! I'm back to the same problem, but I now have a unique identifier column. I just keep getting that "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" exception error. Any thoughts? Take care Ironsmith

                                M 1 Reply Last reply
                                0
                                • I Ironsmith1977

                                  Oh that is awesome, I just did it and it works great. Good to know that I'm not completely screwed! Thank you very much! I'm back to the same problem, but I now have a unique identifier column. I just keep getting that "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" exception error. Any thoughts? Take care Ironsmith

                                  M Offline
                                  M Offline
                                  minhpc_bk
                                  wrote on last edited by
                                  #16

                                  I just did it and it works great Sound better, :) Can you post here what line is causing that error?

                                  I 1 Reply Last reply
                                  0
                                  • M minhpc_bk

                                    I just did it and it works great Sound better, :) Can you post here what line is causing that error?

                                    I Offline
                                    I Offline
                                    Ironsmith1977
                                    wrote on last edited by
                                    #17

                                    This is where it stops:

                                    string id = PurchaseDataGrid.DataKeys[index] as string;

                                    I've tried altering [index], but that didn't work out so well. I've stepped through the code, and really I can't see why this code doesn't work. But this is the first time I'm using this sort of code, not to mention I just started ASP.NET(C#) a few weeks ago. Take care Ironsmith

                                    M 1 Reply Last reply
                                    0
                                    • I Ironsmith1977

                                      This is where it stops:

                                      string id = PurchaseDataGrid.DataKeys[index] as string;

                                      I've tried altering [index], but that didn't work out so well. I've stepped through the code, and really I can't see why this code doesn't work. But this is the first time I'm using this sort of code, not to mention I just started ASP.NET(C#) a few weeks ago. Take care Ironsmith

                                      M Offline
                                      M Offline
                                      minhpc_bk
                                      wrote on last edited by
                                      #18

                                      That's what I'm expecting, do you set the DataGrid.DataKeyField property? , here is the sample code:

                                      private void Page_Load(object sender, System.EventArgs e)
                                      {
                                      if(!IsPostBack)
                                      {
                                      DataTable table = CreateDataSource();

                                          //The ItemID is used as a key to select a specific row in a table.  
                                          //You may probably replace it with your real column name.
                                          PurchaseDataGrid.DataKeyField = "ItemID";
                                                              
                                          PurchaseDataGrid.DataSource = table;
                                          PurchaseDataGrid.DataBind();
                                                         
                                          Session\["Items"\] = table;
                                       }
                                      

                                      }

                                      In addition, you can also set this property in the design window.

                                      I 1 Reply Last reply
                                      0
                                      • M minhpc_bk

                                        That's what I'm expecting, do you set the DataGrid.DataKeyField property? , here is the sample code:

                                        private void Page_Load(object sender, System.EventArgs e)
                                        {
                                        if(!IsPostBack)
                                        {
                                        DataTable table = CreateDataSource();

                                            //The ItemID is used as a key to select a specific row in a table.  
                                            //You may probably replace it with your real column name.
                                            PurchaseDataGrid.DataKeyField = "ItemID";
                                                                
                                            PurchaseDataGrid.DataSource = table;
                                            PurchaseDataGrid.DataBind();
                                                           
                                            Session\["Items"\] = table;
                                         }
                                        

                                        }

                                        In addition, you can also set this property in the design window.

                                        I Offline
                                        I Offline
                                        Ironsmith1977
                                        wrote on last edited by
                                        #19

                                        Well, I had that line of code in the wrong section...I had it in the click event, not the page load. But, it's progress, it got past that line and down to the next where it generated this exception error: "Cannot perform '=' operation on System.Int32 and System.String." This is the line of code:

                                        DataRow[] rows = dt.Select("ItemID='"+ id + "'");

                                        One thing is for certain, I'm learning more here from you than I have from my instructor all year! lol. Ironsmith

                                        M 2 Replies Last reply
                                        0
                                        • I Ironsmith1977

                                          Well, I had that line of code in the wrong section...I had it in the click event, not the page load. But, it's progress, it got past that line and down to the next where it generated this exception error: "Cannot perform '=' operation on System.Int32 and System.String." This is the line of code:

                                          DataRow[] rows = dt.Select("ItemID='"+ id + "'");

                                          One thing is for certain, I'm learning more here from you than I have from my instructor all year! lol. Ironsmith

                                          M Offline
                                          M Offline
                                          minhpc_bk
                                          wrote on last edited by
                                          #20

                                          I also guess this reason then I post all code in the Page_Load event. The key thing is to set that property before the datasource is really bound to the datagrid. Because at binding time, the DataKeys collection will be constructed based on the DataKeyField. If the ItemID column is of the Integer type, you simply remove the apostrophes in code, it will look like this:

                                          DataRow[] rows = dt.Select("ItemID="+ id);

                                          I 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups