Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to export only visible columns from datatable to xml, I have this code

C#
DataTable dt = new DataTable();

foreach (DataGridViewColumn col in dg1.Columns)
{
    dt.Columns.Add(col.HeaderText);
}

foreach (DataGridViewRow row in dg1.Rows)
{
    DataRow dRow = dt.NewRow();

    foreach (DataGridViewCell cell in row.Cells)
    {
        dRow[cell.ColumnIndex] = cell.Value;
    }
    dt.Rows.Add(dRow);
}

DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(saveFileDialog1.FileName);

it works but for all columns
Posted
Updated 21-Nov-12 4:48am
v2
Comments
[no name] 21-Nov-12 8:29am    
You need to remove the inivisible coloums first. Or Write your own customized XML Writer using XDOC.
shonezi 21-Nov-12 8:45am    
how to do this???
ZurdoDev 21-Nov-12 9:19am    
As you are looping through the columns check it's visible property. Did you write this code?
shonezi 21-Nov-12 9:30am    
I have this

for (int i = 0; i < dg1.Columns.Count; i++)
{
if (dg1.Columns[i].Visible)
{
//code
}
}
but its not working

1 solution

See a very similar question I answered for you yesterday?

exporting visible columns of datagridview to csv[^]
 
Share this answer
 
Comments
shonezi 21-Nov-12 12:19pm    
I did mate and I cant get it running on this code :)))
shonezi 21-Nov-12 12:37pm    
I have modified my code to this and it works 500 percent because half of the columns that are hidden in dgv are hidden in exported xml, BUT I have a strange thing also shownand that is that I have 17 columns which are hidden but headertext also gets exported???????and I dont know what to do


DataTable dt = new DataTable();

dt.TableName = "MyTable";
foreach (DataGridViewColumn col in dg1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow gridRow in dg1.Rows)
{
if (gridRow.IsNewRow)
continue;
DataRow dtRow = dt.NewRow();
for (int i = 0; i < dg1.Columns.Count; i++)
if (dg1.Columns[i].Visible)
dtRow[i] = (gridRow.Cells[i1].Value == null ? DBNull.Value : gridRow.Cells[i].Value);
dt.Rows.Add(dtRow);
}

DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(saveFileDialog1.FileName);
shonezi 21-Nov-12 12:37pm    
50 percent :)))
shonezi 21-Nov-12 12:56pm    
I found a problem, code works, its something I did that makes those columsn show up:))
Rob Branaghan 22-Nov-12 5:36am    
Did my original Solution work for you in the end?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900