【问题标题】:C# Display data from program to DataGridViewC# 将数据从程序显示到 DataGridView
【发布时间】:2017-11-07 13:50:34
【问题描述】:

我正在尝试将我从程序中的文本文件中提取的数据显示到 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());
    }
}

}

screenshot

【问题讨论】:

    标签: c# winforms visual-studio list datagridview


    【解决方案1】:

    对于“无法创建抽象类或接口 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 添加 2 列,并将它们的绑定分别设置为 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; }
        }
    }
    

    【讨论】:

    • 感谢您的回复,不幸的是我还没有完全理解您的回答,因为我无法让值实际显示在我的表单中。我已经用我所做的编辑更新了代码
    • @MarkBuckley 首先确保您确实有数据。其次,确保您的 daragridview 确实已添加到您的表单中,而不仅仅是声明。我添加了一个适合我的最小示例。
    • 我复制了你的代码,它可以工作,但我在列的顶部看到一个灰色框,我添加了一个屏幕截图,知道是什么原因造成的吗?
    • 如果你仔细观察,你会发现黑色轮廓比 datagridview 略大。我敢打赌,你以前的空数据网格覆盖了你的新的、正在工作的数据网格。
    • 这是我在设计器的DataGridView框上使用的缩放比例,非常感谢您的帮助!!!
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多