在datagridview中显示数据C#

时间:2017-03-14 08:36:05

标签: c# .net datagridview

我有一个问题我想在DataGridView中显示数据。该脚本获取所有txt文件的处理,并使用每个文件中的正则表达式数据进行搜索。一切都很好。

我的问题是我现在不知道如何在DataGridView中显示结果;

(好像有人可以帮我解决这个问题。请事先感谢你的帮助。

private void button2_Click(object sender, EventArgs e)
{
    string newPath = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\faktury\\");
    string[] filePaths = Directory.GetFiles(newPath, "*.txt");

    foreach (string fp in filePaths)
    {
        string[] lines = File.ReadAllLines(fp);

        // Iterate through lines
        foreach (string line in lines)
        {

            foreach (Match match in Regex.Matches(line, @"(Numer Faktury:|Numer faktury korygującej: )(.*?)$", RegexOptions.IgnoreCase))
            {

                MessageBox.Show(match.Groups[2].Value);

            }
            foreach (Match match in Regex.Matches(line, @"Data wystawienia: (.*?)$", RegexOptions.IgnoreCase))
            {

                MessageBox.Show(match.Groups[1].Value);

            }
            foreach (Match match in Regex.Matches(line, @"Wartość netto  (.*?) PLN", RegexOptions.IgnoreCase))
            {

                MessageBox.Show(match.Groups[1].Value);

            }
            foreach (Match match in Regex.Matches(line, @"Wartość całkowita VAT 8 %  (.*?) PLN", RegexOptions.IgnoreCase))
            {

                MessageBox.Show(match.Groups[1].Value);

            }
            foreach (Match match in Regex.Matches(line, @"Wartość brutto  (.*?) PLN", RegexOptions.IgnoreCase))
            {

                MessageBox.Show(match.Groups[1].Value);

            }
        }

1 个答案:

答案 0 :(得分:1)

您可以在List<T>收集所有结果,并将其最终绑定为DataSource到DataGridView

为此我建议创建一个额外的类,显示属性:

public class ShowResults
{
    public string MatchValue { get; set; }

    // you can of course add as much properties as you want to be display
    // depending on what information you want to share with the user

    public ShowResults(string mv)
    {
        this.MatchValue = mv;
    }    
}

然后继续使用List<ShowResults>

收集结果
string newPath = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\faktury\\");

string[] filePaths = Directory.GetFiles(newPath, "*.txt");

List<ShowResults> results = new List<ShowResults>();

foreach (string fp in filePaths)
{
    string[] lines = File.ReadAllLines(fp);

    foreach (Match match in Regex.Matches(line, @"(Numer Faktury:|Numer faktury korygującej: )(.*?)$", RegexOptions.IgnoreCase))
    {
        results.Add(new ShowResults(match.Groups[2].Value));
    }
    foreach (Match match in Regex.Matches(line, @"Data wystawienia: (.*?)$", RegexOptions.IgnoreCase))
    {
        results.Add(new ShowResults(match.Groups[1].Value));
    }

//... and so on 

最后你会绑定它。

dataGridView1.DataSource = results;