C# datagrid(windows forms)

  • hi,

    i want to write datagrid contents in to a text file

    how to do this.plz help me

    any help will be appriciated

    with regards

    charly

  • What do you mean by datagrid contents ? I assume you are binding something to the datagrid in order to display it. Is it a datatable, array, custom collection ?? Depending on what it is you can write a bit of code to iterate the datasource outputting the contents but what format do you want the output file in ? CSV, Tab Delimited, Fixed Width etc ?

  • I assume you're binding the grid to a dataTable.  The datagrid does not contain any built in methods to output its contents to any file or stream.  The only format the DataSet has is output to XML, which is probably not what you'd like.  Here is some code below as a rough mock up to get a DataTable to a csv file:

     

    DataGrid dg =

    new DataGrid();

    DataSet ds =

    new DataSet();

    ds.Tables.Add("People");

    dg.DataMember = "People";

    dg.DataSource = ds;

    System.IO.StreamWriter sw =

    new System.IO.StreamWriter("Somefile.dat");

    System.Text.StringBuilder sb =

    new System.Text.StringBuilder();

    DataTable dt = ds.Tables["People"];

    dt.Columns.Add("FirstName",

    typeof(string));

    dt.Columns.Add("LastName",

    typeof(string));

    for(int i=0;i<3;i++)

    {

    DataRow r = dt.NewRow();

    r[0] = "Joe";

    r[1] = "Doe";

    dt.Rows.Add(r);

    }

    foreach(DataRow row in dt.Rows)

    {

    foreach(System.Data.DataColumn col in dt.Columns)

    {

    sb.Append(row[col].ToString() + ",");

    }

    sb.Append('\n');

    }

    sw.Write(sb.ToString());

    sw.Close();


    Kindest Regards,

    Paul Krasucki, MCAD

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply