将数据保存到文本文件并将其加载到C#中的数据网格中#

问题描述:

我需要将某些数据传递到文本文件并将该文本文件保存在SQL Server 2005数据库中。将数据保存到文本文件并将其加载到C#中的数据网格中#

然后我需要能够将该文本文件加载到C#WinForms DataGrid中。

如何在C#中执行此操作?

为什么不从SQL Server中的数据读入数据网格,而不是从文本文件中读取吗?将数据从数据库加载到网格中应该很容易。

从您的问题中不清楚数据在哪里开始,或者您为什么需要该文本文件。不过,我会回答你的一点。有很多方法可以读取文本文件。这就是我通常做:

首先,写出一个文件与该模式

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(); 
      } 

然后数据读取使用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的”]是为DataGrid

数据源有关于这种方法在这里信息:

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

+0

跟帖:Windows 7中不支持文本驱动器。 – SeaDrive 2011-11-29 17:45:26