【问题标题】:reading a text document with rows and columns into a datatable, then bind the data table to a gridview将带有行和列的文本文档读入数据表,然后将数据表绑定到gridview
【发布时间】:2017-11-12 11:05:21
【问题描述】:

我有一个如下所示的文本文档:

string string string string string
string string string string string
string string string string string
string string string string string
string string string string string

我们的目标是将这些信息放入网格视图中。并将其显示在 Windows 窗体应用程序中。

到目前为止,我只能通过执行以下操作将信息放入二维数组:

string input = File.ReadAllText("path to the file");

//counters
int i = 0;
int j = 0;

//initialize array
string[,] result = new string[5, 5];

//loop
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var column in row.Trim().Split(' '))
    {
        result[i, j] = column.Trim();
        j++;
    }
    i++;
}

将其放入网格视图的最佳方法是什么?

【问题讨论】:

标签: c# gridview


【解决方案1】:

将数据输入数据表。请参阅下面的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        const string FILENAME = @"c:\temp\test.txt";
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();
            dt.Columns.Add("Col A", typeof(string));
            dt.Columns.Add("Col B", typeof(string));
            dt.Columns.Add("Col C", typeof(string));
            dt.Columns.Add("Col D", typeof(string));
            dt.Columns.Add("Col E", typeof(string));

            StreamReader reader = new StreamReader(FILENAME);
            string inputLine = "";
            while((inputLine = reader.ReadLine()) != null)
            {
                string[] inputArray = inputLine.Split(new char[] { ' ' });
                dt.Rows.Add(inputArray);
            }

            dataGridView1.DataSource = dt;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2014-04-05
    • 2016-03-12
    相关资源
    最近更新 更多