[.net] DataGridView saving

Started by
4 comments, last by Black Knight 16 years, 10 months ago
Hi there. I'm working on an item editor.First I started with a list view but then switched to datagridview because it allows to edit each subitem etc. But I can't seem to find a way to save the data inside it to a file. The DataGridView is not bound to any DataSet. So I can't use WriteXML. How can I convert a DataGridView to a DataSet so I can easily write it to disk? Or Is there any other way to write the values inside a DataGridView to disk. Thanks. Oh and im pretty new to c# and .net so I appreciate every detailed explanation.
Advertisement
After some hours of poking around I managed to save the items to an xml file.
private void ItemEditor_Load(object sender, EventArgs e)        {                       DataTable dt = new DataTable("itemstable");            dt.ReadXmlSchema("items.xml");            dt.ReadXml("items.xml");                                    DataRow row;            itemDataGridView.Rows.Clear();            DataGridViewRow myRow;            for(int i=0; i<dt.Rows.Count-1; i++){                row = dt.Rows;                                                itemDataGridView.Rows.Add(row.ItemArray);                           }                                    			        }        private void saveItemDatabase_Click(object sender, EventArgs e)        {            DataTable dt = new DataTable("itemstable");                         for(int i=0; i<itemDataGridView.ColumnCount; i++){                dt.Columns.Add(itemDataGridView.Columns.Name,typeof(System.String));            }                                    DataRow myrow ;            int icols = itemDataGridView.Columns.Count;             foreach (DataGridViewRow drow in this.itemDataGridView.Rows) {                 myrow = dt.NewRow();                 for (int i = 0; i <= icols - 1; i++) {                                         myrow = drow.Cells.Value;                 }                 dt.Rows.Add(myrow);             }                         dt.WriteXml("items.xml");                    }


Now I'm wondering if there is an easy of writing them to a binary file.
You can create a dataset and set it as the datasource in the datagridview. Then that will allow you to use the writexml method on the dataset.
DataTable allows me to use the WriteXML.Currently I have a working system for writing and loading from items.xml file.
Im just wondering how I will turn that into a binary format.
A friend of mine told me to serialize the datatable I don't know how to do that yet though :|
This is an example from the MSDN documentation on BinaryFormatter that I modified for you. For other kinds of serialization check the System.Runtime.Serialization.Formatters namespace.

Good luck!

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Data;

public class App
{
[STAThread]
static void Main()
{
Serialize();
Deserialize();
Console.ReadLine();
}

static void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
DataTable table = new DataTable();
table.Columns.Add( new DataColumn( "ID", typeof( System.Int32 ) ) );
table.Columns.Add( new DataColumn( "CustName", typeof( System.String ) ) );

// Add some data
DataRow workRow;

for( int i = 0; i <= 9; i++ )
{
workRow = table.NewRow();
workRow [ 0 ] = i;
workRow [ 1 ] = "CustName" + i.ToString();
table.Rows.Add( workRow );
}

// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream( "DataFile.dat", FileMode.Create );

// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize( fs, table );
}
catch( SerializationException e )
{
Console.WriteLine( "Failed to serialize. Reason: " + e.Message );
throw;
}
finally
{
fs.Close();
}
}


static void Deserialize()
{
// Declare the hashtable reference.
DataTable table = null;

// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream( "DataFile.dat", FileMode.Open );
try
{
BinaryFormatter formatter = new BinaryFormatter();

// Deserialize the hashtable from the file and
// assign the reference to the local variable.
table = (DataTable) formatter.Deserialize( fs );
}
catch( SerializationException e )
{
Console.WriteLine( "Failed to deserialize. Reason: " + e.Message );
throw;
}
finally
{
fs.Close();
}

// To prove that the table deserialized correctly,
// display the key/value pairs.
for( int i = 0; i< table.Rows.Count; i++ )
{
Console.WriteLine( "ID: {0}; CustName: {1}",table.Rows[0], table.Rows[1] );
}
}
}
Thank you very much I think thats exactly what Im looking for :)
Ill try to put it in my code and see how it works :]
Thanks again!

This topic is closed to new replies.

Advertisement