开发者

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

I need to Pass some data to a 开发者_StackOverflowtext file and save that text file in a SQL Server 2005 database.

Then I'll need to be able to load that textfile into a C# WinForms DataGrid.

How do I do that in C#?


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


Take a look at this tutorial:

This tutorial demonstrates how to use the Xilytix TFieldedText component to read a CSV file and place the headings and records into a .NET WinForms DataGrid.


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

First, write out a 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 to a 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");

The table ds.Tables["MyTable"] is the DataSource for the DataGrid

There is info about this method here:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜