update datatable inside a dataset - c#

I want to know how to update a Datatable which is inside a dataset.I have a datatable in which i have details of some item.Now i want to add this into a dataset for some purpose and update it.Give me some suggesions to solve this..
this is my code:
DataRow dr;
dr = Basket_DataTable.NewRow();
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
Basket_DataTable.AcceptChanges();
Basket_DataTable is my datatable which i need to add to a dataset and update..

I believe you want to add new Rows to your existing DataTable in your DataSet. Instead of creating a new DataTable, your Basket_DataTable should refer to your data table in the data set.
Something like.
//Create new Row from your DataTable in DataSet
DataRow dr = yourDataSet.Tables["Basket_DataTable"].NewRow();
// here you can refer to your datatable with the index as well
//e.g. yourDataSet.Tables[0]
Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();
//Remember to add your row to the table.
yourDataSet.Tables["Basket_DataTable"].Rows.Add(dr);
In your current code you are not adding the new row to the datatable. Remember to include the row in the datatable.

If the DataTable is already in an existing DataSet, but you want to add it to another one, you need to create a copy first - A DataTable instance can only have one parent DataSet.
DataTable Basket_DataTable_copy = Basket_DataTable.Copy();
yourDataSet.Tables.Add(Basket_DataTable_copy);
Then you can do your updates on Basket_DataTable_copy
see DataTable.Copy on MSDN

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!

Alternative Ways In Adding New Rows in Datasource Data Grid View

I'm creating a project in C# windows form. What I'm trying to do is add new rows in the datasource data grid view. But the problem is, the error says that adding new rows can't add programmatically in the datasource data grid.
Here's my method in fetching the data and transfer it in the data grid view.
public DataTable GetData(ClassName classVar){
SqlCommand cmd = new SqlCommand();
cmd.Connection = ...; // My connection string
cmd.CommandType = CommandType.Text;
cmd.CommandText = ...; // My Query
DataTable table = new DataTable();
table = ...ExeReader(cmd);
return table;
}
The Codes inside my form
DataTable getDataTable;
getDataTable = ClassQuery.GetData(classVar);
dgv_details.DataSource = getDataTable;
And this is my add button
dgv_details.Rows.Add(txtBox1.Text,txtBox2.Text);
What are the alternative ways in adding data inside the datasourced datagridview?
Thanks in advance.
Try the below code. First add row to datatable and then bind that table to datagridview.
DataRow dr = datatable1.NewRow();
dr[0] = "HAI"; // add data in first column of row
datatable1.Rows.InsertAt(dr, 0); // insert new row at position zero
datatable1.Rows.Add(dr); // addnew row at last

Copy one datatable to another datatable in asp.net

I have created a datatable which has some records, now what I want is to copy the record of first datatable to another datatable.
I tried like below:
Session["AmountData"] = AmountDatatable; // 1st datatable which has data
DataTable CompanyWiseRecord = new DataTable();
for (int i = 0; i < AmountDatatable.Rows.Count; i++)
{
CompanyWiseRecord.ImportRow(AmountDatatable.Rows[i]); // 2nd datatable which does not have data
}
Kindly let me know where I am going wrong.
You directly use session Like:
DataTable CompanyWiseRecord = (DataTable)Session["AmountData"]; //Retrieving DataTable from Session.
if you are not fetching data from table one based on some condition or assign particular rows or columns then You can do it simply by using
DataTable CompanyWiseRecord=AmountDatatable;

How to add filtered row From Table inside Dataset that already get 3 other Tables?

I've problem in adding another Table and this is my Code
rptSalarList3_En SalaryListReport3 = new rptSalarList3_En();
ds = clsReports.ViewSalaryPaySlipListReport(parameters[0], PaySlip3.dtmFromDate, PaySlip3.dtmToDate);
dsReports.Tables.Clear();
dsReports.Tables.Add(ds.Tables[0].Copy());
dsReports.Tables.Add(ds.Tables[1].Copy());
dsReports.Tables.Add(ds.Tables[2].Copy());
DataTable dt1 = dsReports.Tables[0].Copy();
DataRow Dr = dt1.Rows[0];
DataRow[] result = dsReports.Tables[0].Select("SalaryItemName = 'Variable'");
dt1.Rows.Clear();
dt1.Rows.Add(result[0].ItemArray);
DataSet DsTaxable = new DataSet();
DsTaxable.Tables.Add(dt1);
dsReports.Tables.Add(DsTaxable.Tables[0]);
dsReports.Tables.Add(dsLogo.Tables[0].Copy());
dsReports.Tables[0].TableName = "SalaryListItems";
dsReports.Tables[1].TableName = "Preferences";
dsReports.Tables[2].TableName = "SalaryItemDetails";
dsReports.Tables[3].TableName = "SalaryItemTaxable";
The Problem is when having filter from first table it raise error message that said
(ex.Message = "DataTable already belongs to another DataSet.")
and I want to take the Filtered value from First Table and make it Table so I can add it To dsReports to Show in Crystal Report
Using .Copy() like other Tables helped me to get same data from first table which need to be filtered
and can added to current DataSet

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.

Categories