In my c# code I am trying to create an excel report with my data. I was trying some way to give my data headers. So I called my stored procedure added my dataset tables and now I want to add one of those tables to be a row in my data table. It returns one row my dataset does. example of how I want it to look:
Title
93.76% 00:23:59 00:33:41 95.56% 00:57:40 94.66%
Seems simple enough that's why I choose datatable to do so with and not dataset because I was limited to the dataset tables formatting. How can I get my data table to display the the data and not the name? Code provided below. I am also up for any other suggestions on how to accomplish this. If you need any more info or code please feel free to ask.
var dt = new DataTable("IncomingProductReport");
dt.Columns.Add("A Line Down Time");
SqlCommand cmd = new SqlCommand("L_GetTimeTotals", conn);
cmd.Parameters.Add("#startTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker2.SelectedDate;
cmd.Parameters.Add("#endTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker3.SelectedDate;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var ds = new DataSet();
ds.Tables.Add("IncomingProductTotals");
ds.Tables.Add("IncomingProductTotalsA");
ds.Tables.Add("IncomingProductTotalsB");
ds.Tables.Add("IncomingProductTotals1");
ds.Tables.Add("IncomingProductTotalsA1");
ds.Tables.Add("IncomingProductTotalsB1");
da.TableMappings.Add("Table", "IncomingProductTotals");
da.TableMappings.Add("Table1", "IncomingProductTotalsA");
da.TableMappings.Add("Table2", "IncomingProductTotalsB");
da.TableMappings.Add("Table3", "IncomingProductTotals1");
da.TableMappings.Add("Table4", "IncomingProductTotalsA1");
da.TableMappings.Add("Table5", "IncomingProductTotalsB1");
da.Fill(ds);
ds.Tables.Remove("IncomingProductTotalsA");
ds.Tables.Remove("IncomingProductTotalsB");
ds.Tables.Remove("IncomingProductTotalsA1");
ds.Tables.Remove("IncomingProductTotalsB1");
dt.Rows.Add("Line 1 Totals");
dt.Rows.Add(ds.Tables["IncomingProductTotals"]);
dt.Rows.Add("Line 2 Totals");
dt.Rows.Add(ds.Tables["IncomingProductTotals1"]);
ExcelHelper.ToExcel(dt, "DownTimeTotals.xls", Page.Response);
dt.Columns.Add("A Line Down Time");
You are adding a Column to the DataTable. You do not say what type so it will be the default type and that is string.
dt.Rows.Add(ds.Tables["IncomingProductTotals"]);
Then you try to put a complete DataTable into a cell of a Column that expects strings. To get a string from the given object the system will call the ToString method of the DataTable. And ToString is implemented as returning the Tablename of a DataTable.
You need to take the data in the DataTables to put into the dt DataTable not the DataTables itself. That makes no sense. Allowed types for a column if you really wanted to put a DataTable into a DataTable are only the once described here.
Related
I only want data not header column names from the DataTable result set. or is it possible to create a DataTable without column headers. i tried every possible scenario but couldn't get anything.
above
Is my sp result, which I can very easily convert into DataTable. But I don't want to header row. there is option in SQL where we can include or exclude the column headers but even that is not working
Your help is highly appreciated.
this is my test c# code
DataTable table = new DataTable();
SqlCommand cmd = new SqlCommand("Rmtest1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#unitName", SqlDbType.VarChar).Value = unitName;
cmd.Parameters.Add("#startdate", SqlDbType.VarChar).Value = startDate;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
So basically I want the rows but not the headers
As far as I know, you cant hide/remove the column header, but you can change the column header name with some string space (" ") to make the column header looks like blank.
You can't hide column header from DataTable. But you can hide it from your displaying control. I'm not sure which control you want to use for your case, but you can use the following code to hide it from DataGridView in WinForm App.
dgwStudents.ColumnHeadersVisible = false;
I am trying to copy a row from one table to another in same dataset.
code I am using
dsFrom.Tables["asd2"].Rows.Add(dsFrom.Tables["asd"].Rows[0].ItemArray);
I am getting an NullRefferenceException. I've determined that Rows are null, even though there is data in both tables. Can anyone explain why is this happening? Or maybe there is another solution for my problem.
Thanks
EDIT
This is how I am loading data in them
string query = #"select * from table1;
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet dsFrom = new DataSet();
da.Fill(dsFrom, "asd");
da.Fill(dsFrom, "asd2");
May be you should try to copy rows by this way:
foreach (var row in dsFrom.Tables["asd"].Rows)
{
dsFrom.Tables["asd2"].ImportRow(row);
}
i want to create a for loop in which i want to write a query which updates the the value of each row in database. the rows are present in the datagridview as well as in the database. the aim is when the changes are made in datagridview so using a button the change are also applied in the database table too. in each row the barcode and its quantity is different. if the changes are made in all the rows in datagridview so it is also to be applied in database using button and also please help with the parameters.
here is the query which should be considered in the for loop:
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
consider barcode as column1 and item_quantity as column2.
so far to create a for loop i have tried this but getting error in the for loops:
for (int i = 0; dataGridView2.Rows.Count; i++) //getting error here
{
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
cmd2.Parameters.AddWithValue("#barcode", dataGridView2.Rows[i].Cells[1].Value.ToString());
cmd2.Parameters.AddWithValue("#qty", dataGridView2.Rows[i].Cells[1].Value.ToString());
}
you should call cmd2.ExecuteNonQuery(); in your loop ... otherwise no sql commands will be executed
to get a better solution you should move to creation of cmd2 before the loop. also add the parameters there (without assigning values) ... inside the loop just assign the values and call ExecuteNonQuery.
maybe the best solution would be to use databinding and a SqlDataAdapter with assigned UpdateCommand.
just saw that there probably is an error in your code ... you use the value from Cell[1] for both of your parameters ...
example:
first create a DataTable ... var dt = new DataTable();
then add the columns you want in your grid to the DataTable ... dt.Columns.Add("xyz");
then attach the DataTable to your grid: dataGridView2.DataSource = dt;
now you should be able to edit the contents of column "xyz". to write the values to the database you create a SqlDataAdapter ... var adp = new SqlDataAdapter();
then set adp.InsertCommand = new SqlCommand(...) and adp.UpdateCommand = new SqlCommand(...)
now you can call adp.Update(); and all the values from your grid are written to db ... for newly added rows the InsertCommand is invoked and for edited rows the UpdateCommand is invoked.
I've got an assignment which requires me to update the northwind database,
I've done everything like the tutorials say as follows
I fill The DataTable Using The DataAdapter.Fill(table).
I build the Delete,Insert,Update Commands using CommangBuilder
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.DeleteCommand = builder.GetDeleteCommand(true);
adapter.UpdateCommand = builder.GetUpdateCommand(true);
adapter.InsertCommand = builder.GetInsertCommand(true);
adapter.Fill(employees_table);
I also set a primary key for the table:
DataColumn[] employees_keys = new DataColumn[2];
employees_keys[0] = employees.Columns["EmployeeID"];
employees_table.PrimaryKey = employees_keys;
Now I've attempted to delete and add a row:
// accepts an employee object and creates a new new row with the appropriate values for
// an employee table row
DataRow row = ConvertEmployeeToRow(employeeToAdd);
employee_table.Rows.Add(row);`
and deleting a row:
DataRow row = employees.Rows.Find(employeeToDismiss.ID);
employees.Rows.Remove(row);
I should also point out that I've attempted to use row.SetAdded() and row.Delete()
Anyway, at the end when I try to update the database
int k = employees_adapter.Update(employees_table);
on added rows sometimes k get valued, on remove never, and in either case nothing really gets updated at all in the database itself.
Any insight of what I'm doing wrong?
Make sure you're calling employee_table.AcceptChanges() after the call to Update() to save the changes to the database.
Check if the CommandBuilder really makes an Update command for you, like this:
MessageBox.Show(adapter.UpdateCommand.CommandText);
If the primary key info is missing it won't build the update command at all!
I am little confuse here your SqlDataAdapter name is adapter and you are doing updation in employees_adapter.The steps are so simple to work with SqlDataAdapter just follow theses
Step No 1:
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable employees_table= new DataTable ();
adapter.Fill(employees_table);
Step No 2:
After you got the data in dataset start manipulation on it..
To insert :
DataRow MyRow = employees_table.NewRow();
//Now Fill data in MyRow
employees_table.Tables[0].Rows.Add(MyRow);
employees_table.AcceptChanges();
adapter.Update(employees_table);
To Delete :
/get only the rows you want
DataRow[] result = employees_table.Select("ID ="+id); //id will be provided by you
//Now do here data updation
employees_table.AcceptChanges()
adapter.Update(employees_table);
Like wise you can apply updation..But after doing any changes must call
table.AcceptChanges() and then'adapter.Update(employees_table)'
Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...
I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.
EDIT:
The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}". Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!
EDIT 2:
I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.
Am starting to wonder if it is a probelm with:
dt.Load(sqlReader);
The data does appear after this step though in the dataset visualiser, but not after being cloned.
Code below.
All help very welcome!
Thanks in advance
Chris
1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.
DataTable dt = new DataTable();
SqlDataReader sqlReader= default(SqlDataReader);
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sqlReader);
System.Web.HttpContext.Current.Session["ResultsTable"] = dt;
2) Part of the code in a class which performs calculations on the table:
DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];
did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:
System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();