Removing items from a datagrid???
-
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 -
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 IronsmithHi 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[^]
-
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[^]
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 -
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! IronsmithWhat 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. :)
-
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'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
-
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
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[^]
-
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 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
-
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
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.
-
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 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
-
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
-
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
-
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
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.
-
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.
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
-
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
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[^]
-
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[^]
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
-
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
-
I just did it and it works great Sound better, :) Can you post here what line is causing that error?
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
-
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
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.
-
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.
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
-
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
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);