且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在窗口应用程序中将文本文件加载到数据网格视图中

更新时间:2022-01-26 03:20:18


您可以遍历文件,然后将它们添加到DataTable中.然后,您可以将DataTable绑定到您的DataGridView.
阅读文本文件的帖子:
http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx [ ^ ]
有关DataTable的帖子:
http://www.dotnetperls.com/datatable [
Hi,
You can iterate through your file and then add them to a DataTable. then, you can bind the DataTable to your DataGridView.
A post to read a text file:
http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx[^]
A post about DataTable:
http://www.dotnetperls.com/datatable[^]

I hope it helps,
Cheers


可以使用以下代码将问题中指定格式的文本文件中包含的数据读入DataTable,并将DataTable绑定到DataGridView.
The data contained in the text file in the format specified in the question can be read into a DataTable and the DataTable can be bound to a DataGridView using the following code
void Main()
{
	Form form1 = new Form();
	DataGridView dataGridView1 = new DataGridView();
	dataGridView1.Dock= DockStyle.Fill;

        //Read the data from text file
	string[] textData = System.IO.File.ReadAllLines(dataFileName);
	string[] headers = textData[0].Split(',');

        //Create and populate DataTable
	DataTable dataTable1 = new DataTable();
	foreach(string header in headers)
	    dataTable1.Columns.Add(header,typeof(string),null);
	for(int i=1; i < textdata.length; i++)
            dataTable1.Rows.Add(textData[i].Split(','));

        //Set the DataSource of DataGridView to the DataTable
	dataGridView1.DataSource = dataTable1;
	form1.Controls.Add(dataGridView1);
	form1.ShowDialog();
}