How to copy DataGridView contents to Dataset? - ado.net

i'm not good with ADO.NET
so used the following code that i got from Internet
but i get the error "There is no row at position 0." # the marked line(*)
even though i can see a value is being passed using breakpoints
DataSet ds = new DataSet();
DataTable dt = new DataTable("ProdFromDGV");
ds.Tables.Add(dt);
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, typeof(string));
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
*dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString();*
}
}
dt.WriteXml("table.xml");

You need to first create a DataRow type and add it into your DataTable before you can start assigning to it.
So your code will now be something like:
DataSet ds = new DataSet();
DataTable dt = new DataTable("ProdFromDGV");
ds.Tables.Add(dt);
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, typeof(string));
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
// This will not work, but it's something similar to this that you need here...
DataRow row = new DataRow();
dt.RowCollecion.Add(row);
// Now you can assign to the row....
dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString();
}
}
dt.WriteXml("table.xml");
Hope this helps some..

// This will not work, but it's something similar to this that you need here...
Just change
DataRow row = new DataRow();
to:
DataRow row = dt.NewRow();
and it will work.

Related

How can we write data to excel Template and maintain the template format in OpenXML?

I am able to read the excel template using openxml, and able to append data to the sheets.
But unable to maintain the existing Excel Template format, and unable to identify the column headings
Please find the below code used
if (ds.Tables.Count > 0 && ds.Tables[0] != null || ds.Tables[0].Columns.Count > 0)
{
System.Data.DataTable table = ds.Tables[0];
using (var spreadsheetDocument = SpreadsheetDocument.Open(filePath, true))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
Sheet sheet = spreadsheetDocument.WorkbookPart.Workbook.Sheets.GetFirstChild<Sheet>();
Worksheet worksheet = (spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id.Value) as WorksheetPart).Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
List<String> columns = new List<string>();
IEnumerable<Row> rows = worksheet.GetFirstChild<SheetData>().Descendants<Row>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
}
foreach (DataRow row in table.Rows)
{
Row newRow = new Row();
columns.ForEach(col =>
{
Cell cell = new Cell();
//If value is DBNull, do not set value to cell
if (row[col] != System.DBNull.Value)
{
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(row[col].ToString());
}
newRow.AppendChild(cell);
});
sheetData.AppendChild(newRow);
}
spreadsheetDocument.WorkbookPart.Workbook.Save();
spreadsheetDocument.Close();
}
Please find actual excel screenshot
please find expected excel screenshot
Please clarify your specific problem and provided the actual code snippet and the example template that you are using so we can better understand your issue and assist you on the issue.
There is earlier post “OpenXML SDK 2.5 Excel Template" Find a label in template with name DataField, and replace with data. This might be what you are looking for.

How to add rows to TableView without having any data model

I'm fairly new to javafx, so please bear with me if my question is unclear. I've a TableView which need to be populated using an ObservableList.
The code below populates my "data" with the arraylists generated out of the Map, which in turn is used to add rows to my table.
TableView<ArrayList> table = new TableView<>();
ObservableList<ArrayList> data = FXCollections.observableArrayList();
for(int i=0;i<listSelectedVerticesIds.size();i++){
ArrayList<String> tempString = new ArrayList<>();
for(Map.Entry<String,String> temp2 : mapVertex.get(listSelectedVerticesIds.get(i)).entrySet()){
tempString.add(temp2.getValue());
}
data.add(tempString);
}
table.setItems(data);
However, I do not see the table populated with the list in "data". I'm guessing this is because there is no data binding (using setCellValueFactory). However, as you can see I dont have a data model class. All of my data comes from the Map as strings which I would like to populate in my tableview.
Please suggest.
Here is a simple way to do it that works great. You don't need a data structure to populate a table. You only see that because that's what most examples show. It is an extremely common use case to populate a table from a database or a file. I don't understand why this is so hard to find examples for. Well, hope this helps.
private TableView<ObservableList<StringProperty>> table = new TableView<>();
private ArrayList<String> myList = new ArrayList<>();
private void updateTableRow() {
for (int row = 0; row < numberOfRows; row++) {
ObservableList<StringProperty> data = FXCollections.observableArrayList();
for (int column = 0; column < numberOfColumns; column++) {
data.add(column, new SimpleStringProperty(myList.get(row + (column * numberOfRows))));
}
table.getItems().add(data);
}
}

Devexpress xtraChart How to assign x and y values?

I have values in datasource and there is no problem with datasource. I have to assign X and Y values to the chart. Chart throws an error and says there is no column with named "TotalInboundArrivals".
ChartControl chart = new ChartControl();
chart.Location = new Point(38, 301);
chart.Size = new Size(789, 168);
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
series.DataSource = ds;
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "TotalInboundArrivals"; //throws error here
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "StartTime" }); //throws error here
((SideBySideBarSeriesView)series.View).ColorEach = true;
((XYDiagram)chart.Diagram).AxisY.Visible = true;
chart.Legend.Visible = true;
chart.Visible = true;
chart.Dock = DockStyle.Fill;
xtraTabPage1.Controls.Add(chart);
Where is my Problem? Any Suggestions?
Have you went through Series.DataSource Property. You are making the mistake of assigning DataSet as DataSource to series. Think about it, how could it search columns in Data Source. Try to assign Ds.Tables["TableName"] as the datasource.
Creating DataSource Table
private DataTable CreateChartData(int rowCount) {
// Create an empty table.
DataTable table = new DataTable("Table1");
// Add two columns to the table.
table.Columns.Add("Argument", typeof(Int32));
table.Columns.Add("Value", typeof(Int32));
// Add data rows to the table.
Random rnd = new Random();
DataRow row = null;
for (int i = 0; i < rowCount; i++) {
row = table.NewRow();
row["Argument"] = i;
row["Value"] = rnd.Next(100);
table.Rows.Add(row);
}
Specifying Series properties corresponding to datasource
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
// Generate a data table and bind the series to it.
series.DataSource = CreateChartData(50);
// Specify data members to bind the series.
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "Argument";
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "Value" });
Check the Examples and go through the Creating Charts -> Providing Data section to better understand it.
Reference
Hope this helps.

Entity Framework, one-to-many, several columns

If I have a main table, lets say orders, and a sub table of items and the items table has a fields for item number BUT it also has a nullable (optional) field for color that applied only to certain items. How would I update the items table, at the same time as the orders table, using Entity Framework?
Here is a code example of what I have so far. Two problems, I'm only entering one of my items and, from what my research indicates, I can't add another field to the items table?
foreach (Guid c in AllItems)
{ Items.OrderItemID = Guid.NewGuid();
ITemsOrderID = order.OrderID;
ITems.ItemID = c;
If (ItemID = ItemThatLetsYouChoseAColorID)
{
Items.ItemColorID = ColorID;
} else {
Items.ItemColorID = null;
}
}
context.Orders.AddObject(Orders);
context.Items.AddObject(Items);
context.SaveChanges();
My Orders table gets a record inserted, and the Items gets ONE record inserted. I'm missing something basic here, I'm afraid. BTW, this is Entity Framework 4.0, which. I believe, does not require the use of EntityKey.
You're adding an object to the Items collection only one time after the scope of your foreach.
Have you tested something like:
foreach (Guid c in AllItems)
{
var Item = new Item();
Item.OrderItemID = Guid.NewGuid();
Item.OrderID = order.OrderID;
Item.ItemID = c;
If (ItemID = ItemThatLetsYouChoseAColorID)
{
Item.ItemColorID = ColorID;
}
else
{
Item.ItemColorID = null;
}
context.Items.AddObject(Items);
}
context.Orders.AddObject(order);
context.SaveChanges();
And I'm not sure to understand what you mean by
I can't add another field to the items table
You should be more precise about what you actually expect. Insert a row, add a column in the table...? What is a "field"?
Here is the working code. I had the new Item outside the foreach item loop, so was overwriting the value. Also, I need to add each one to the context. I had a hard time with this, hope it helps someone else:
<-fill the order object->
foreach (Guid i in Items)
{
**Items item = new Items();**
item.ItemID = Guid.NewGuid();
item.OrderID = order.OrderID;
if (i == ItemWithColorGuid)
{
foreach (Guid c in Colors)
{
**Items color = new Items();**
color.ItemsID = Guid.NewGuid();
color.OrderID = order.orderID;
color.itemID = g;
color.colorID = c;
context.item.AddObject(color);
}
}
else
{
item.ItemID = i;
item.ColorID = null;
context.item.AddObject(item);
}
}
context.orders.AddObject(order);
context.SaveChanges();

Creating Subtables in Piwik

I am new to piwik.Please help me in my issue.
Issue: I have to create 4 levesl of subtables.Currently I can able to create upto 2nd level,I mean table with one subtable per row.
Basically If I click on a table row I shoud get the subtable.If I click on subtable row again it should show inner subtable.
I need to create Table->subtable->subtable->subtable.
My code :
function getpageViewsLevel1($idSite, $date, $period)
{
$query = "select * from....";
$result = Piwik_FetchAll($query, array($idSite, $dateStart, $dateEnd));
// convert this array to a DataTable object
$dataTable = new Piwik_DataTable();
//Add subtable to each result
foreach ($result as $arr){
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setColumns($arr);
$subDataTable = new Piwik_DataTable();
$piwik_row->addSubTable($subDataTable);
$dataTable->addRow($piwik_row);
}
return $dataTable;
}
function getpageViewsLevel2($idSite, $date, $period, $idSubtable)
{
// Find selected parent row and retrieve data
$dataTable_old = $this->getpageViewsLevel1($idSite, $date, $period);
$row_old = new Piwik_DataTable_Row;
$row_old=$dataTable_old->getRowFromIdSubDataTable($idSubtable+1);
$tmp=$row_old->getColumns();
//Using $actionName in DB Query
$actionName=$tmp['pageTitle'].'%';
//db query
$query = "select * ....";
$result = Piwik_FetchAll($query, array($idSite, $dateStart, $dateEnd, $actionName));
// convert this array to a DataTable object
//$dataTable = new Piwik_DataTable();
foreach ($result as $arr){
$piwik_row = new Piwik_DataTable_Row;
$piwik_row->setColumns($arr);
$subDataTable = new Piwik_DataTable();
$piwik_row->addSubTable($subDataTable);
$dataTable->addRow($piwik_row);
}
return $dataTable;
}
Till here works fine.For the 3rd level,I am not able to apply the same logic as I dont have the 2ng level table ID.
function getpageViewsLevel3($idSite, $date, $period, $idSubtable)
{
// Find selected parent row and retrieve data
$dataTable_old = $this->getpageViewsLevel2($idSite, $date, $period, ___???????????????);
Please help me how can I proceed with this issue.Please let me know is there any other solution to do this.
Though if I pass some number like '1' for testing,
$dataTable_old = $this->getpageViewsLevel2($idSite, $date, $period, 1);----->this is not working.
I need to use parent row info in my DB query.
Thanks in advance for your help.