-2

How to store the input from a file in grid view in a C# console application and display it in a grid view of rows and columns?

I want to skip some lines in the text file, and then store it in grid view.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using System.IO;

namespace projectyj1
{
    public partial class Form1 : Form
    {
        public Form1()
        {


InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("time", typeof(String));
        dt.Columns.Add("active_power_avg", typeof(Int32));
        dt.Columns.Add("active_power_max", typeof(Int32));
        dt.Columns.Add("active_power_min", typeof(Int32));


using (StreamReader sr = new StreamReader(@"D:\Data\mean\yo1.txt"))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            string[] parts = line.Split(';');
            var row = dt.NewRow();
            for (int i 

= 0; i < parts.Length; i++)
                {
                    row[i] = parts[i];
                }
            // important thing!
            dt.Rows.Add(row);
        }
        sr.Close();
    }
wp78de
  • 18,207
  • 7
  • 43
  • 71
  • 1
    What exactly is your question? What isn't working or where are you stuck? – David Mar 10 '17 at 11:29
  • See this answer. http://stackoverflow.com/questions/4418319/c-sharp-how-to-skip-number-of-lines-while-reading-text-file-using-stream-reader – Wheels73 Mar 10 '17 at 11:30
  • Side note: For reading CSV style files, try TextFieldParser in the Microsoft.VisualBasic.FileIO namespace. – ProgrammingLlama Mar 10 '17 at 12:06

1 Answers1

1

If you want to skip some lines from text file while writing to DataTable: provide if condition and continue keyword (to move to a next iteration of your for cycle) while you're reading a row from your text file.

Something like that (pseudocode):

if parts contains "value":
     continue

More: https://msdn.microsoft.com/en-us/library/0ceyyskb.aspx

Vlad Rudskoy
  • 677
  • 3
  • 7
  • 24