简体   繁体   中英

C# Display data from program to DataGridView

I'm trying to display data that I pulled from text files within my program to a DataGridView but I'm having trouble finding out how to do it, another problem I have is that when the form opens it stops running through the code.

Here is the main part of my code:

DataGridView dataGridView = new DataGridView();
IList<Machine> machines = new BindingList<Machine>();
dataGridView.DataSource = machines;


SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"

        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);


                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();


            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }



            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                //Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                //Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);


                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);


            }
        }

        Application.Run(new Form1());
    }
}

}

screenshot

For your specific error of "cannot create an instance of the abstract class or interface IList", the problem is that you're trying to create an instance of an interface. You want a concrete class. For example, List implements IList so you can do

IList<string> names = new List<string>();

An interface is basically just a contract describing what a class that implements it can do.

As for you question, you want to create a class to hold your data, parse your files into objects, put them in a BindingList or any other appropriate collection then bind your datagridview to that collection.

class Machine
{
    public string Name {get; set;}
    public decimal CashCount {get; set;}
}

public static void main()
{
    IList<Machine> machines = new BindingList<Machine>();

    foreach(string fileName in fileNames)
    {
        //read your files, put data in a Machine object
        Machine m =new Machine();
        m.Name=nm[0];
        m.CashCount=MCC1[0];
        //add it to the list
        machines.add(m);
    }

    //then bind the collection to your datagridview
    datagridView.Datasource = machines;
}

Then in your form designer, you can add 2 columns to the datagridview and set their binding to Name and CashCount respectively. You could also, for example, set the format of the CashCount columns to be displayed as money.


Edit: adding minimal working example

using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace datagridview
{
    public partial class Form1 : Form
    {
        private DataGridView dgvMachines;

        public Form1()
        {
            InitializeComponent();
            //this is the Designer.cs code...
            this.dgvMachines = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgvMachines)).BeginInit();
            this.SuspendLayout();
            // 
            // dgvMachines
            // 
            this.dgvMachines.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvMachines.Location = new System.Drawing.Point(12, 12);
            this.dgvMachines.Name = "dgvMachines";
            this.dgvMachines.Size = new System.Drawing.Size(606, 400);
            this.dgvMachines.TabIndex = 0;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(630, 434);
            this.Controls.Add(this.dgvMachines);
            this.Name = "Form1";
            this.Text = "Form1";
            ((ISupportInitialize)(this.dgvMachines)).EndInit();
            this.ResumeLayout(false);

            IList<Machine> machines = new BindingList<Machine>();
            dgvMachines.DataSource = machines;
            machines.Add(new Machine { Name = "#1", CashCount = 100 });
            machines.Add(new Machine { Name = "#2", CashCount = 200 });
            machines.Add(new Machine { Name = "#3", CashCount = 300 });
            machines.Add(new Machine { Name = "#4", CashCount = 400 });
        }
    }

    class Machine
    {
        public string Name { get; set; }
        public decimal CashCount { get; set; }
    }
}

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM