簡體   English   中英

C#將數據從程序顯示到DataGridView

[英]C# Display data from program to DataGridView

我正在嘗試顯示從程序中的文本文件提取到DataGridView的數據,但是我很難找到方法,我遇到的另一個問題是,當窗體打開時,它會停止運行代碼。

這是我的代碼的主要部分:

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());
    }
}

}

屏幕截圖

對於“無法創建抽象類或接口IList的實例”的特定錯誤,問題在於您正在嘗試創建接口的實例。 您需要一個具體的課程。 例如,List實現IList,因此您可以執行

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

一個接口基本上只是一個契約,描述了實現它的類可以做什么。

關於您的問題,您想要創建一個類來保存數據,將文件解析為對象,將它們放入BindingList或任何其他適當的集合中,然后將datagridview綁定到該集合。

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;
}

然后,在表單設計器中,您可以將兩列添加到datagridview並將其綁定分別設置為Name和CashCount。 例如,您還可以將CashCount列的格式設置為顯示為貨幣。


編輯:添加最小的工作示例

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; }
    }
}

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM