Saving data to text file and loading it into datagrid in C #

I need to pass some data to a text file and save this text file in a SQL Server 2005 database.

Then I will need to load this text file into C # WinForms DataGrid.

How can I do this in C #?

+2


a source to share


3 answers


+1


a source


Why not read data from SQL Server into a datagrid rather than read it from a text file? Loading data from a database into a grid should be easy out of the box.



+2


a source


It is not clear from your question where the data starts from, or why you need a text file. However, I will answer one of your questions. There are many ways to read a text file. This is how I usually do it:

First write the file with the schema

using (StreamWriter sw = new StreamWriter(sPath + @"\schema.ini"))

            {
                sw.WriteLine("[" + sFile + "]");
                sw.WriteLine("ColNameHeader=False");
                sw.WriteLine("Format=FixedLength");
                sw.WriteLine("Col1=CO_ID Text Width 2");
                sw.WriteLine("Col2=AGENCY_CD Text Width 10");
                // lines for additional columns here
                sw.Close();
                sw.Dispose();
            } 

      

Then read the data into the DataSet using ODCB.

            string cs = @"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" + sPath;
            OdbcConnection cn = new OdbcConnection(cs);
            string q = @"select * from [" + sNewFN + "]";
            OdbcDataAdapter da = new OdbcDataAdapter(q, cn);
            da.Fill(ds, "MyTable");

      

Ds.Tables ["MyTable"] is the DataSource for the DataGrid

There is information about this method here:

http://msdn.microsoft.com/en-us/library/ms714091%28v=VS.85%29.aspx

+1


a source







All Articles