Delete specific row in dynamically generated gridview - c#

I have a small GridView that will hold certain items. This is the code that generates the gridview after a user clicks an item:
if (grdCarritoAddons.Rows.Count == 0)
{
dt.Columns.Add(new DataColumn("Name", typeof(System.String)));
dt.Columns.Add(new DataColumn("Price", typeof(System.String)));
}
else
{
dt = HttpContext.Current.Session["DataTable"] as DataTable;
}
Session["DataTable"] = dt;
DataRow dr1 = dt.NewRow();
dr1[0] = AddonName.ToString();
dr1[1] = Convert.ToDecimal(PriceAddon);
dt.Rows.Add(dr1);
grdCarritoAddons.DataSource = dt;
grdCarritoAddons.DataBind();
}
Now I need a user to be able to select an item and delete a specific one. In the ASPX page I already added the Delete Command and created an empty RowDeleting method in code and on the GridView properties. It isn't working, and I came up with a solution that somewhat works but isn't what I need to do. It basically wipes out the whole DataTable.
//grdCarritoAddons.DataSource = dt;
//grdCarritoAddons.DataBind();
//Session["DataTable"] = dt;
//Session.Remove("Total");
I tried this:
grdCarritoAddons.Rows.RemoveAt(grdCarritoAddons.SelectedRows[0].Index);
But no go. Doesn't work in ASP. Thanks for any help :)
Current Code:
dt = HttpContext.Current.Session["DataTable"] as DataTable;
dt.Rows.RemoveAt(grdCarritoAddons.SelectedRow.RowIndex);
But its throwing an Object reference not set to an instance of an object exception. If I put an IF to check if the row is null it won't execute at all... but the data is obviously not empty.

This is the Error: 'System.Web.UI.WebControls.GridViewRowCollection'
does not contain a definition for 'RemoveAt' and no extension method
'RemoveAt' accepting a first argument of type
'System.Web.UI.WebControls.GridViewRowCollection' could be found
Yes, this method does not exist as you can see here. You should modify the datasource instead and databind the grid afterwards. DataRowCollection has a RemoveAt method.
dt.Rows.RemoveAt(grdCarritoAddons.SelectedRow.RowIndex);
grdCarritoAddons.DataSource = dt;
grdCarritoAddons.DataBind();

Related

Datatable values to datagridview, only showing one columns data

I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:
// Create DataTabe to handle the output
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")
Fill the new datatable:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(string.Join(",", row.ColumnValues));
}
Then I try to bind the data in the datatable to the dataGridview:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?
Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)
foreach (ReportRow row in report.Rows)
{
DataRow dr = dt.NewRow();
dr["EmployeeFirstName"] = row["EmployeeFirstName"];
dr["EmployeeLastName"] = row["EmployeeLastName"];
dr["DepartmentName"] = row["DepartmentName"];
//rest of the columns fill
//once all columns filled
dt.Rows.Add(dr);
}
dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.
From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.
string.Join(",", row.ColumnValues) is one object.
Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(row.ColumnValues);
}
Thank you all for your responses!

Gridview show controls (labels, buttons, textfields) even if Datasource is null

How can I show my controls even if my table columns are null using gridview? All I know is ShowHeaderWhenEmpty="true"
If datasource of gridview is null, you can create a temporery datatable and assign it as a datasuource of gridview.
if (GridView1.DataSource == null)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr[0] = "";
dt.Rows.Add(dr);
GridView1.DataSource=dt;
GridView1.DataBind();
}
If your data is NULL then there is no data to show. In order to show the controls, you need to have data.
I'd try to create a dummy row if the db returns null.
if(db.rows.count < 1)
{
//add a row with dummy values
}
Hope this helps.
you can try this:
dataGridView1.Rows.Add(num_rows);

DataGridview gives null values in its columns even after manually populating them

I have used DataGridview, which is supposed to be populated manually (No data sources specified). I want to get its content of first row(index-0). But it gives me null cell values.
Code
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Description");
dt.Columns.Add("Unit Price");
dt.Columns.Add("Quantity");
dt.Columns.Add("Tot");
dr = dt.NewRow();
dr[0] = dataGridViewA_General.Rows[0].Cells[1].Value; //these values are null
dr[1] = dataGridViewA_General.Rows[0].Cells[2].Value; //these values are null
dr[2] = dataGridViewA_General.Rows[0].Cells[3].Value; //these values are null
dr[3] = dataGridViewA_General.Rows[0].Cells[4].Value; //these values are null
dt.Rows.Add(dr);
Thanks in advance
Updated
// dataGridViewA_General
this.dataGridViewA_General.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewA_General.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column_A_item_code,
this.Column_A_description,
this.Column_A_qntity,
this.Column_A_unit_price,
this.Column_A_list_total});
// Column_A_description
this.Column_A_description.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Column_A_description.HeaderText = "Description";
this.Column_A_description.Name = "Column_A_description";
// Instantiate
private System.Windows.Forms.DataGridView dataGridViewA_General;
private System.Windows.Forms.DataGridViewTextBoxColumn Column_A_description;
(rest of the columns are also defined in the sameway.)
You must add the row to the DataTable.
dt.Rows.Add(dr);
NewRow(); simply creates a blank row, you must add it manually.
Also, as you didn't put anything in the row itself, nothing will be returned.
I had done done a logical mistake and code had not been executed in expected manner after filling data. Actually the above code is correct. Thank you all for your valuable contribution.

C# DataGridView data-bound error with Grid.Rows.Add method

i have a DataGridView on the Form. I select some data from database and load them to datatable and after that i make reference this datatable to grid's datasorurce as below.
string sql = "";
sql = "SELECT id,name,surname,code FROM t_persons";
DataTable dt = new DataTable();
...
adapter.Fill(dt);
grid.DataSource = dt;
and after that i want to add new row to this grid with grid.Rows.Add() method. But every time it gives an error Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.
So whatis the problem and how can i solve it.
You should add row to the DataTable, not to the DataGridView. That is what the exception is saying. Try:
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
Please you can add row directly to datatable and it's effect on gridview because it's bind to datatable.

Can't update data in datagridview

Goal:
Having two buttons that should be enable to add or delete data from datagridview. The changes should be make in real time so you should be see the new result.
Problem:
Having problem to display the new result after I have used button add functionality because the result won't display in real time. In order to view the result I have to close and reopen the application in order to view the new result.
Please remember that I don't use a database.
I'm using class table and then I connect the table to the datagridview's datasource.
DataTable table = new DataTable();
table.Columns.Add("a");
table.Columns.Add("b");
foreach (var a in myManagerProduct.GetAllProductList())
{
DataRow row;
row = table.NewRow();
row["a"] = a._articleNumber;
row["b"] = a._name;
dgridStock.Rows.Add(row);
table.Rows.Add(row);
}
dgridStock.DataSource = table;
Try following code snippet to add new row to the grid.
DataView dv = ((dgridStock.BindingContext[dgridStock.DataSource] as CurrencyManager).List as DataView);
DataRowView rowView = dv.AddNew();
rowView["a"] = a._articleNumber;
rowView["b"] = a._name;
rowView.EndEdit();
And make sure dgridStock.DataSource = table; is set only once. After that every addition shouldn't refresh the DataSource property.
As Sanjeevakumar Hiremath said, don't forget EndEdit() command for row or DataTable in general. After finishing all the operations about inserting, updating and deleting data, call DataGridView.Refresh().

Categories