I am trying to copy data from my datagridview to a datatable so i can export to a csv file
here is the code
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
}
return dsptable;
}
It seems like it copies the data from the the grid to to the table but when I return the datatable all there is the columns no rows
You are not adding dataRow to data table after assigning values to its columns.
public DataTable createdatatablefromdgv()
{
DataTable dsptable = new DataTable();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
DataColumn dspcolumn = new DataColumn(dataGridView1.Columns[i].HeaderText);
dsptable.Columns.Add(dspcolumn);
}
int noOfColumns = dataGridView1.Columns.Count;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
DataRow dataRow = dsptable.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dgvr.Cells[i].Value.ToString();
}
dsptable.Rows.Add(dataRow); //Add this statement to add rows to Data Table
}
return dsptable;
}
The above answer is correct but a little explanation as to why you encountered this problem. One would think that by calling NewRow() on the DataTable you would add a new row to the DataTable and then be able to access it.
What NewRow actually does is give you an instance of a DataRow which you can then use column names as apose to column identifiers (integers).
This allows you to do something like this
DataRow dataRow = dsptable.NewRow();
foreach(DataColumn dc in dsptable.Columns)
{
dataRow[dc.ColumnName] = dgvr.Cells[dc.ColumnName].Value.ToString()
}
Alternatively you could just call Rows.Add() which takes an object array or a as you were trying to do a DataRow.
List<string> rowData = new List<string>();
for (int i = 0; i < noOfColumns; i++)
{
rowData.Add(dgvr.Cells[i].Value.ToString());
}
dsptable.Rows.Add(rowData.ToArray());
This should explain adding rows to a datatable more simply :)
Related
I have a datatable loaded into my datagridview.
One functionality is to send a Mail to all selected recipients.
Before doing so I have to get the selected data first out of my raw datatable.
However, if I have a huge datatable and want to look for the checked cells, the whole process takes too long (1-3 minutes).
private DataTable GetDataTable()
{
DataTable sdt = new DataTable(); //"Selected Datatable"
int i = 0;
for (int z = 0; z < dataGridView1.Columns.Count; z++) // Add Columns to Datatable sdt
sdt.Columns.Add(dataGridView1.Columns[z].HeaderText);
foreach (DataGridViewRow Row in dataGridView1.Rows)
{
if (Convert.ToBoolean(Row.Cells["CheckboxHeader"].Value)) // Go on if Checkbox is checked
{
sdt.Rows.Add();
for (int j = 1; j < dataGridView1.ColumnCount; ++j)
{
sdt.Rows[i][j] = Row.Cells[j].Value;
}
i++;
}
}
return sdt;
}
How can I access all the checked Rows at once?
Hi Can any one suggest how to read data from datagrid in windowsforms application which has two columns(FileName and FilePath).
Below is the code I tried its returning all Filename and FilePath in single column(FileName).
Any suggestions would be helpful to me..
`
public System.Data.DataTable ExportToExcel()
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
{
for (int col= 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
{
table.Rows.Add(dataGridView1.Rows[rows].Cells[col].Value.ToString());
}
}
The issue is that the line…
table.Rows.Add(dataGridView1.Rows[rows].Cells[col].Value.ToString());
is only adding to the FIRST column. You are adding a new row for EACH column.
To add a row to a table that has two columns would be of the form…
table.Rows.Add(column1Value, column2Value);
Since you know there are TWO columns, simply loop through the rows. It is not necessary to loop through the columns.
DataTable table = new DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
for (int rows = 0; rows < dataGridView1.Rows.Count; rows++) {
if (!dataGridView1.Rows[rows].IsNewRow &&
dataGridView1.Rows[rows].Cells[0].Value != null &&
dataGridView1.Rows[rows].Cells[1].Value != null) {
table.Rows.Add(dataGridView1.Rows[rows].Cells[0].Value.ToString(), dataGridView1.Rows[rows].Cells[1].Value.ToString());
}
}
If it is unknown how many columns are in the DataGridView and you must loop through the columns… then you will need to make sure there are at least as many columns in the DataGridView as there are columns in the DataTable.
DataTable table = new DataTable();
table.Columns.Add("FileName", typeof(string));
table.Columns.Add("FilePath", typeof(string));
DataRow newRow;
if (dataGridView1.Columns.Count >= table.Columns.Count) {
for (int row = 0; row < dataGridView1.Rows.Count; row++) {
if (!dataGridView1.Rows[row].IsNewRow) {
newRow = table.NewRow();
for (int col = 0; col < table.Columns.Count; col++) {
if (dataGridView1.Rows[row].Cells[col].Value != null)
newRow[col] = dataGridView1.Rows[row].Cells[col].Value.ToString();
else
newRow[col] = "";
}
table.Rows.Add(newRow);
}
}
}
If you know what object dataGridView1.DataSource is, just visit the object. It would be much easier.
Besides, there's a simple way to export data from DataGridView to Excel:
Ctrl+A Select all cells in DataGridView.
Ctrl+C Copy them.
Ctrl+V Paste them in a sheet of Excel.
I've to do the transpose of my DataTable and I used the code I found in internet. This code is giving an extra row at the top showing the column index. How can I remove this row?This extra row is at above the header row of my DataTable, and when I use the code dt_.Rows.Remove(dt_.Rows[0]); the header row is removed but not the top row. Reference taken from:
Transpose a datatable
How can I remove the top row?
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k - 1][j];
}
table.Rows.Add(dr);
}
dt_ = table;
//dt_.Rows.Remove(dt_.Rows[0]); removes the header row
My gridview code
<asp:GridView ID="GridView1"
runat="server"
CellPadding="3"
CellSpacing="2"
AutoGenerateColumns="true"
ShowFooter="true"
FooterStyle-HorizontalAlign="Left"
RowStyle-BorderColor="Black" HeaderStyle-BackColor="#0CA3D2">
<FooterStyle BackColor="#87CEFA" />
</asp:GridView>
I've not shown the footer section sum calculation code behind because it is irrelevant here.
snapshot:
I think if you start the loop from 1 it should work
DataTable dt = new DataTable();
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
//HERE THE LOOK STARTS FROM ONE
for (int j = 1; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k - 1][j];
}
table.Rows.Add(dr);
}
dt_ = table;
That's because
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
is creating columns named 0, 1, and 2. the problem is with Convert.ToString(i). That, and you will also need to change how you read k.
The code will look like this (not tested):
DataTable dt_ = new DataTable();
DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(dt.Rows[i][0]); // the column name is in the first cell
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
// changed the for condition
for (int k = 1; k < dt.Rows.Count; k++)
{
dr[k] = dt.Rows[k][j]; // changed the 'k - 1' to 'k'
}
table.Rows.Add(dr);
}
dt_ = table;
How to add a row in the data table
Code
DataTable dt = new DataTable();
dt.Clear();
DataColumn dc = new DataColumn("day1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("day3", typeof(String));
dt.Columns.Add(dc);
tString[0] = "Sat,mon,tue";
tString[1] = "Fri,,wed";
tString[2] = "Thu,";
int lengthA = tString.Length;
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
foreach (string word in words)
{
dt.Rows.Add(word);
}
}
The issue in dt.Rows.Add(word) because it is inserting a row
Expected Output
Datatable value should be
day1, day2, day3
sun,mon,tue
Fri,Wed
Thu
Hot to achieve this, can any one help me
Just create a NewRow() and then add the values to its Item indexer for each column.
for (int i = 0; i <= lengthA - 1; i++)
{
string s = tString[i];
string[] words = s.Split(',');
// here is the new row
var row = dt.NewRow();
for(int w = 0; w < words.Length; w++)
{
// set each column
row[w] = words[w];
}
// don't forget to add the Row to the Rows collection
dt.Rows.Add(row);
}
I'm trying to add only the selected rows of a DataGridView to a DataTable, the code that I'm using always start from the first row even if this one is not selected... Does someone have an idea for how to fix this please?
DataTable dt = new DataTable("Rapport");
// Generating columns to datatable
foreach (DataGridViewColumn column in dataGridView1.Columns)
dt.Columns.Add(column.Name, typeof(string));
// Adding selected rows of DGV to DataTable
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
dt.Rows.Add();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
dt.Rows[i][j] = dataGridView1[j, i].Value;
}
}
You have to access SelectedRows like
dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
Also its better if your DataTable has the same type as of Cell
DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
dt.Columns.Add(column.Name, column.CellType); //better to have cell type
So your code would be:
DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
dt.Columns.Add(column.Name, column.CellType); //better to have cell type
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
dt.Rows.Add();
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
//^^^^^^^^^^^
}
}
DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
{
dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
}
dt.AcceptChanges();