I cannot get my dataGridView to update with all the tables in the dataSet. I just get one row in the dataGridView after I try to populate it.
I call this to fill my dataSet:
DataTable table = new DataTable(DateTime.Now.ToString());
table.Columns.Add("c1");
table.Columns.Add("c2");
table.Columns.Add("c3");
table.Columns.Add("c4");
table.Columns.Add("c5");
table.Columns.Add("c6");
table.Columns.Add("c7");
table.Rows.Add("s1", "s2", "s3", "s4", "s5", "s6", "s7");
dataSet1.Tables.Add(table);
dataSet1.WriteXml("MyData.xml");
The data is written fine, but if I try to read it with this I only get one row populated, even if there's multiple entries in the dataSet.
dataSet1.ReadXml("MyData.xml");
MessageBox.Show((dataSet1.GetXml()));
I get the message with the data in the correct format, with the correct number of entries.
dataGridView2.AutoGenerateColumns = true;
int i2 = 0;
while (i2 < dataSet1.Tables.Count)
{
dataGridView2.DataSource = dataSet1.Tables[i2];
i2++;
}
After this it will only show one row and not the amount of tables. The dataSet1.Tables.Count >= 2, but still only get 1 row.
Edit: It seems that each time I call this line:
dataGridView2.DataSource = dataSet1.Tables[i2];
It is deleting the previous row. Is there any way to append the row instead?
You only created one table in the data set, so your while statement only executes once:
while (i2 < dataSet1.Tables.Count)
{
...
}
Count = 1 (number of tables) because you only called dataSet1.Tables.Add(table); one time.
dataSet1.WriteXml("MyData.xml") is only writing out the schema for that single table. So reading it back in will only read back in a single table's worth of schema.
The following code appears to count the number of tables in the dataset:
while (i2 < dataSet1.Tables.Count)
Try pointing this to the table:
dataSet1.Tables["Yourtable"].Count
Related
I have an existing datatable called _longDataTable containing data. Now, I want to duplicate each row and in each duplicate of the row, I want to set only the value in the SheetCode column according to a value from a different datatable called values, see code below. For example, the values datatable contains 1, 2 and 3, then I want each row of _longDataTable to be duplicated three times and in each of the duplicated rows, I want the Sheet Code column to have values 1, 2 and 3 respectively. My code now looks like below:
foreach (DataRow sheets in _longDataTable.Rows)
{
for(int k = 0; k < number_of_sheets; k++)
{
var newRowSheets = _longDataTable.NewRow();
newRowSheets.ItemArray = sheets.ItemArray;
newRowSheets["SheetCode"] = values.Rows[k]["Sheet Code"];
//add edited row to long datatable
_longDataTable.Rows.Add(newRowSheets);
}
}
However, I get the following error:
Collection was modified; enumeration operation might not execute.
Does anyone know where this error comes from and how to solve my problem?
you get enumeration error because you are iterating through a collection which is changing in the loop(new rows added to it),
as you said in the comment, you get out of memory exception because you are iterating on the _longDataTable, then you add rows to it, the iteration never reach to end and you will get out of memory exception.
I assume this can help you:
//assume _longDataTable has two columns : column1 and SheetCode
var _longDataTable = new DataTable();
var duplicatedData = new DataTable();
duplicatedData.Columns.Add("Column1");
duplicatedData.Columns.Add("SheetCode");
foreach (DataRow sheets in _longDataTable.Rows)
{
for (int k = 0; k < number_of_sheets; k++)
{
var newRowSheets = duplicatedData.NewRow();
newRowSheets.ItemArray = sheets.ItemArray;
newRowSheets["SheetCode"] = values.Rows[k]["Sheet Code"];
newRowSheets["Column1"] = "anything";
//add edited row to long datatable
duplicatedData.Rows.Add(newRowSheets);
}
}
_longDataTable.Merge(duplicatedData);
do not modify _longDataTable, add rows to the temp table (with the same schema) and after the iteration merge two data tables.
Background
I have a set of numbers between 1000-9999 split between two data tables both with same the Schema. One data table's schema is then cloned, and then filled with the rows from both of the original tables. This third new data table is then displayed in a datagridview.
Question
How could I then highlight the rows in the datagridview that contain rows from the first data table?
Code
private void combineTables()
{
bothIdsTbl = UsedIdsTbl.Clone();
dataGridView3.DataSource = bothIdsTbl;
for (int i = 0; i <= UnUsedIdsTbl.Rows.Count - 1; ++i)
{
bothIdsTbl.ImportRow(UnUsedIdsTbl.Rows[i]);
}
for (int i = 0; i <= UsedIdsTbl.Rows.Count - 1; ++i)
{
bothIdsTbl.ImportRow(UsedIdsTbl.Rows[i]);
}
dataGridView3.Sort(this.dataGridView3.Columns["stationid"], ListSortDirection.Ascending);
}
The best solution would be the following:
Add a "flag" column to 3rd table before filling it,
Put in that column a value indicating wheteher the row was imported or not from 1st table.
Use the CellFormatting event of the DataGridView to change
cells backcolor according to the flag column.
You can use a command named merge to combine the two datatables.
If this data came from a database you may consider a union query or any other option to combine the data or obtain all the data in one call.
I am trying to save a new added row in a DataGridView to a database. I can't understand which method to call - either gridview1_UserAddedRow or gridview1_RowsAdded (what if it's just one row?).. So far, I've seen that gridview1_RowsAdded executes every time when the form loads.
The DataGridView is bound using a BindingList.
This is how the gridview1_UserAddedRow looks like:
private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
int lastRow = dataGridView1.Rows.Count - 2;
DataGridViewRow newRow = dataGridView1.Rows[lastRow];
bindinglist.Add(new MyTestClass{ ScheduleId = scheduleId, Name = Convert.ToString(newRow.Cells["Name"].Value),
Value = Convert.ToString(newRow.Cells["Value"].Value), TestId = testId});
}
Unfortunately, this doesn't work and nothing is inserted. Actually, I think this event is called when a new row is clicked. How else can I insert the newly created row in the database?
The code is not updating anything to the database as there is no code to update it.
You need to execute a query to update those new values. You could try using Commands:
http://msdn.microsoft.com/en-us/library/aa984369(v=vs.71).aspx
Or change the list to a DataTable, which allows you to update the values 'automatically' (a bit harder): http://msdn.microsoft.com/en-us/library/z1z2bkx2(v=vs.110).aspx
I would stay away form databinding, but if you can't, you can try this:
// Create a new row
DataRow dr = YourDataSet.Vendors.NewRow(); // Change 'Vendors' with your database table's name
// Add some data to your new row
dr[0] = 124;
// Insert the previous row
YourDataSet.Vendors.Rows.InsertAt(dr, 1); // Change the 1 to your index where you want to insert the data.
I have a filtered data view, from which I have to extract the values. Problem is that when I do this, I am getting the values from non filtered data also.
dv1.RowFilter = "collegeno=" +i;
for(int k=1;k<dv1.count;k++)
{
//inserting data in database; there is column in database table; I am inserting into it;
dv1.Table.Rows[k]["roomno"]);
}
For ex: The total no. of rows in DataView is 200;
When i=1 I have 30 records;
If I supply k=4, then I should get fourth row from this 30 records.
But I am getting 4th row of the 200 records..
The code you have written is accessing the main table using the code block dv1.Table.
Instead try as this
dv1[k]["roomno"]
This code works on DataView, on which the filter is applicable.
If you use DataView.Table then it will access the non-filtered results.
Reference Link: MSDN - DataView.RowFilter
If I supply k=4, then I should get fourth row from this 30 records.
But I am getting 4th row of the 200 records..
That's because you're querying the table, not the view. Instead you should do this:
dv1.RowFilter = "collegeno=" +i;
object value = dv1[k]["roomno"];
Depending on what you need, you might want to use the DataTable.Select method instead of a DataView:
var rows = table.Select("collegeno=" +i);
object value = rows[k]["roomno"];
DataTable dt = dv.ToTable();
for(int k=1;k<dt.Rows.Count;k++)
{
dt.Rows[k]["roomno"];
//dv1.Table.Rows[k]["roomno"]);
}
I have one asp.net datatable and I want to databind into two asp.net datalists, so I though to slice the datatable rows in two datatables both the same size if even .
Use the Take LINQ extension method to specify how many items to use.
And the Skip to jump over if needed.
var half = myList.Take(myList.Count / 2);
If you are slicing by rows, you can simply create a copy of your original data table, find a suitable half way point, and just import the rows into the copy, while deleting them from the original.
Something like the following should work:
DataTable originalTable = new DataTable();
//Load the data into your original table or wherever you get your original table from
DataTable otherTable = originalTable.Copy(); //Copys the table structure only - no data
int rowCount = originalTable.Rows.Count;
int wayPoint = rowCount / 2; //NB integer division rounds down towards 0
for(int i = 0; i <= wayPoint; i++)
{
otherTable.ImportRow(originalTable.Rows[i]); //Imports (copies) the row from the original table to the new one
originalTable.Rows[i].Delete(); //Marks row for deletion
}
originalTable.AcceptChanges(); //Removes the rows we marked for deletion