【问题标题】:How to have a DataGridView inside a panel that has a header-row that scrolls with horizontal but not with vertical when the panel scrolls如何在面板内有一个 DataGridView,该面板的标题行在面板滚动时水平滚动但不垂直滚动
【发布时间】:2016-10-13 18:48:05
【问题描述】:

我有一个 DataGridView,它使用面板进行滚动以避免可怕的“跳转到列表开头”DataGridView 刷新问题。

我正在寻找的是在垂直滚动期间保持可见并随着水平滚动移动的标题行。

我在 Visual Studio 2012 中测试了这段代码,所以它应该可以立即使用。

Form1.designer.cs

namespace DataGridViewPanel
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel1 = new System.Windows.Forms.Panel();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.panel1.AutoScroll = true;
            this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.panel1.Controls.Add(this.dataGridView1);
            this.panel1.Location = new System.Drawing.Point(12, 73);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(260, 177);
            this.panel1.TabIndex = 0;
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(0, 0);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.None;
            this.dataGridView1.Size = new System.Drawing.Size(257, 174);
            this.dataGridView1.TabIndex = 0;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(13, 41);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Clear";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(197, 41);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 2;
            this.button2.Text = "Add Row";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.panel1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.panel1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
    }
}

Form.cs

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;

namespace DataGridViewPanel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fillDataGrid();
        }

        private void fillDataGrid()
        {
            dataBase Db = new dataBase();
            List<dataBase> DbList = new List<dataBase>();
            for (int i = 0; i < 10; i++)
            {
                DbList.Add(Db);
            }

            dataGridView1.DataSource = DbList;
            int width = 0;
            int height = 0;
            foreach (DataGridViewColumn col in dataGridView1.Columns) width += col.Width;
            foreach (DataGridViewRow row in dataGridView1.Rows) height += row.Height;
            dataGridView1.Size = new Size(width, height);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataBase Db = new dataBase();
            List<dataBase> DbList = new List<dataBase>();

            DbList.Add(Db);


            dataGridView1.DataSource = DbList;
            int width = 0;
            int height = 0;
            foreach (DataGridViewColumn col in dataGridView1.Columns) width += col.Width;
            foreach (DataGridViewRow row in dataGridView1.Rows) height += row.Height;
            dataGridView1.Size = new Size(width, height);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            dataBase Db = new dataBase();
            List<dataBase> DbList2 = new List<dataBase>();

            DbList2 = (List<dataBase>)dataGridView1.DataSource;

            dataGridView1.DataSource = null;

            DbList2.Add(Db);


            dataGridView1.DataSource = DbList2;
            int width = 0;
            int height = 0;
            foreach (DataGridViewColumn col in dataGridView1.Columns) width += col.Width;
            foreach (DataGridViewRow row in dataGridView1.Rows) height += row.Height;
            dataGridView1.Size = new Size(width, height);
        }


    }

    public class dataBase : IEnumerable<string>
    {
        public string one { get; set; }
        public string two { get; set; }
        public string three { get; set; }
        public string four { get; set; }
        public string five { get; set; }
        public string six { get; set; }
        public string seven { get; set; }
        public string eight { get; set; }
        public string nine { get; set; }
        public string ten { get; set; }

        public IEnumerator<string> GetEnumerator()
        {
            yield return one;
            yield return two;
            yield return three;
            yield return four;
            yield return five;
            yield return six;
            yield return seven;
            yield return eight;
            yield return nine;
            yield return ten;
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}

【问题讨论】:

  • 我们或许应该关注:"Jump to beginning of list" DataGridView refresh issue.
  • 修改数据源,不存在“可怕的跳转开始”问题。如果您删除数据源并提供一个新数据源,那么您正在重新开始
  • 我的数据源是一个列表如果我添加一行来更新列表,DataGridVeiw1 @Plutonix 不会发生任何变化
  • BindingList 比 List 更好
  • BindingList 运行良好。我已经举了一个例子。

标签: c# scroll datagridview panel header-row


【解决方案1】:

我通过重叠面板实现了一个可行的解决方案。 我创建了第二个面板和 DataGridView。我用标题填充第二个数据网格。 panel1.Scroll 在水平滚动上处理以移动 panel2 滚动。 因为 panel1 与 panel2 的滚动条重叠,所以滚动处理程序中的最终 panel1.BringToFront() 确保 panel1 隐藏了 panel2 滚动条。

Form1.Designer.cs

namespace DataGridViewPanel
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        this.panel1 = new System.Windows.Forms.Panel();
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.panel2 = new System.Windows.Forms.Panel();
        this.dataGridView2 = new System.Windows.Forms.DataGridView();
        this.panel1.SuspendLayout();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        this.panel2.SuspendLayout();
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit();
        this.SuspendLayout();
        // 
        // panel1
        // 
        this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.panel1.AutoScroll = true;
        this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
        this.panel1.Controls.Add(this.dataGridView1);
        this.panel1.Location = new System.Drawing.Point(13, 107);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(260, 207);
        this.panel1.TabIndex = 0;
        this.panel1.Scroll += panel1_Scroll;
        // 
        // dataGridView1
        // 
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.ColumnHeadersVisible = false;
        this.dataGridView1.Location = new System.Drawing.Point(0, 0);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.ReadOnly = true;
        this.dataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.None;
        this.dataGridView1.Size = new System.Drawing.Size(257, 204);
        this.dataGridView1.TabIndex = 0;
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(13, 41);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "Clear";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        // 
        // button2
        // 
        this.button2.Location = new System.Drawing.Point(197, 41);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(75, 23);
        this.button2.TabIndex = 2;
        this.button2.Text = "Add Row";
        this.button2.UseVisualStyleBackColor = true;
        this.button2.Click += new System.EventHandler(this.button2_Click);
        // 
        // panel2
        // 
        this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.panel2.AutoScroll = true;
        this.panel2.Controls.Add(this.dataGridView2);
        this.panel2.Location = new System.Drawing.Point(13, 84);
        this.panel2.Name = "panel2";
        this.panel2.Size = new System.Drawing.Size(260, 42);
        this.panel2.TabIndex = 1;
        // 
        // dataGridView2
        // 
        this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView2.Location = new System.Drawing.Point(0, 0);
        this.dataGridView2.Name = "dataGridView2";
        this.dataGridView2.Size = new System.Drawing.Size(257, 40);
        this.dataGridView2.TabIndex = 3;
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 326);
        this.Controls.Add(this.panel2);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.Controls.Add(this.panel1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.panel1.ResumeLayout(false);
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        this.panel2.ResumeLayout(false);
        ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit();
        this.ResumeLayout(false);

        }



        #endregion

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.DataGridView dataGridView1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.DataGridView dataGridView2;
    }
}

Form1.cs

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;

namespace DataGridViewPanel
{
    public partial class Form1 : Form
    {
        private dataBase Db = new dataBase();
        private List<dataBase> DbList = new List<dataBase>();
        private List<dataBase> headList = new List<dataBase>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            fillDataGrid();
        }

        private void fillDataGrid()
        {
            //add ten rows to the List
            for (int i = 0; i < 10; i++)
            {
                DbList.Add(Db);
            }

            //add one row to the List to populate headers
            headList.Add(Db);

            //populate datagrid by setting datasource
            dataGridView1.DataSource = DbList;
            dataGridView2.DataSource = headList;

            resizeDataGrids();

        }

        private void resizeDataGrids()
        {
            //resize the datagrids so the panels enable the scrollbars when required

            int width = 0;
            int height = 0;
            foreach (DataGridViewColumn col in dataGridView1.Columns) width += col.Width;
            foreach (DataGridViewRow row in dataGridView1.Rows) height += row.Height;
            dataGridView1.Size = new Size(width, height);

            width = 0;
            height = 0;
            foreach (DataGridViewColumn col in dataGridView2.Columns) width += col.Width;
            foreach (DataGridViewRow row in dataGridView2.Rows) height += row.Height;
            dataGridView2.Size = new Size(width, height);

            //bring panel1 to front
            panel1.BringToFront();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //populate datagridview1 with an empty List
            DbList = new List<dataBase>();
            DbList.Add(Db);
            dataGridView1.DataSource = DbList;
            resizeDataGrids();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //populate datagridview1 with List after adding a new row to the List
            DbList = (List<dataBase>)dataGridView1.DataSource;
            dataGridView1.DataSource = null;
            DbList.Add(Db);
            dataGridView1.DataSource = DbList;
            resizeDataGrids();
        }

        void panel1_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e)
        {
            //Handle horizontal scroll
            if (e.ScrollOrientation == System.Windows.Forms.ScrollOrientation.HorizontalScroll)
            {

                panel2.HorizontalScroll.Value = panel1.HorizontalScroll.Value;
                panel1.BringToFront();
            }
        }

    }

    public class dataBase : IEnumerable<string>
    {
        public string one { get; set; }
        public string two { get; set; }
        public string three { get; set; }
        public string four { get; set; }
        public string five { get; set; }
        public string six { get; set; }
        public string seven { get; set; }
        public string eight { get; set; }
        public string nine { get; set; }
        public string ten { get; set; }

        public IEnumerator<string> GetEnumerator()
        {
            yield return one;
            yield return two;
            yield return three;
            yield return four;
            yield return five;
            yield return six;
            yield return seven;
            yield return eight;
            yield return nine;
            yield return ten;
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}

【讨论】:

    【解决方案2】:

    正如@Plutonix 所建议的,我尝试只更新数据源。

    使用一对 for 循环,我填充了一个连接到 DataGridView1 数据源的数据集。我喜欢这个,因为它消除了面板。

    我仍然可以使用列表!

    感谢@Plutonix!

    Form1.designer.cs

    namespace DataGridViewPanel
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows Form Designer generated code
    
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(13, 41);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Clear";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(197, 41);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 2;
            this.button2.Text = "Add Row";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // dataGridView1
            // 
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(13, 102);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(259, 212);
            this.dataGridView1.TabIndex = 3;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 326);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            }
    
    
    
            #endregion
    
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.Button button2;
            private System.Windows.Forms.DataGridView dataGridView1;
        }
    }
    

    Form1.cs

    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;
    
    namespace DataGridViewPanel
    {
        public partial class Form1 : Form
        {
            private dataBase Db = new dataBase();
            private List<dataBase> DbList = new List<dataBase>();
            private DataSet Ds = new DataSet();
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                //createColumns();
                createColumns();
    
                fillDataGrid();
    
                //populate datagrid by setting datasource
                dataGridView1.DataSource = Ds.Tables[0];
            }
    
            private void AddRow()
            {
                dataBase db = new dataBase();
                db.one = DateTime.Now.Day.ToString();
                db.two = DateTime.Now.Month.ToString();
                db.three = DateTime.Now.Year.ToString();
                db.four = DateTime.Now.Hour.ToString();
                db.five = DateTime.Now.Minute.ToString();
                db.six = DateTime.Now.Second.ToString();
                db.seven = DateTime.Now.Millisecond.ToString();
    
                DbList.Add(db);
    
                fillDataGrid();
            }
    
            private void fillDataGrid()
            {
    
                for (int i = DbList.Count - 1; i > Ds.Tables[0].Rows.Count - 1; i--)
                {
                    Ds.Tables[0].Rows.Add();
                    int loop = 0;
                    foreach (string valueStr in DbList[i])
                    {
                        int end = Ds.Tables[0].Rows.Count - 1;
                        Ds.Tables[0].Rows[end][loop] = valueStr;
                        loop++;
                    }
    
                }
    
    
            }
    
            private void createColumns()
            {
                this.Invoke(new MethodInvoker(delegate
                    {
                        Ds.Tables.Add(new DataTable());
                        Ds.Tables[0].Columns.Add("one");
                        Ds.Tables[0].Columns.Add("two");
                        Ds.Tables[0].Columns.Add("three");
                        Ds.Tables[0].Columns.Add("four");
                        Ds.Tables[0].Columns.Add("five");
                        Ds.Tables[0].Columns.Add("six");
                        Ds.Tables[0].Columns.Add("seven");
                        Ds.Tables[0].Columns.Add("eight");
                        Ds.Tables[0].Columns.Add("nine");
                        Ds.Tables[0].Columns.Add("ten");
                    }));
    
            }
    
    
            private void button1_Click(object sender, EventArgs e)
            {
                //populate datagridview1 with an empty List
                DbList = new List<dataBase>();
                Ds.Clear();
    
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                //populate datagridview1 with List after adding a new row to the List
                //Ds.Tables[0].Rows.Add(Db);
                AddRow();
            }
    
    
        }
    
        public class dataBase : IEnumerable<string>
        {
            public string one { get; set; }
            public string two { get; set; }
            public string three { get; set; }
            public string four { get; set; }
            public string five { get; set; }
            public string six { get; set; }
            public string seven { get; set; }
            public string eight { get; set; }
            public string nine { get; set; }
            public string ten { get; set; }
    
            public IEnumerator<string> GetEnumerator()
            {
                yield return one;
                yield return two;
                yield return three;
                yield return four;
                yield return five;
                yield return six;
                yield return seven;
                yield return eight;
                yield return nine;
                yield return ten;
            }
            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return this.GetEnumerator();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      @LarsTech 建议的 BindingList 解决方案。与 List/DataSet/DataGridView 相比,这非常简单。

      Form1.Designer.cs

      namespace DataGridViewPanel
      {
          partial class Form1
          {
              /// <summary>
              /// Required designer variable.
              /// </summary>
              private System.ComponentModel.IContainer components = null;
      
              /// <summary>
              /// Clean up any resources being used.
              /// </summary>
              /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
              protected override void Dispose(bool disposing)
              {
                  if (disposing && (components != null))
                  {
                      components.Dispose();
                  }
                  base.Dispose(disposing);
              }
      
              #region Windows Form Designer generated code
      
              /// <summary>
              /// Required method for Designer support - do not modify
              /// the contents of this method with the code editor.
              /// </summary>
              private void InitializeComponent()
              {
              this.button1 = new System.Windows.Forms.Button();
              this.button2 = new System.Windows.Forms.Button();
              this.dataGridView1 = new System.Windows.Forms.DataGridView();
              this.button3 = new System.Windows.Forms.Button();
              ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
              this.SuspendLayout();
              // 
              // button1
              // 
              this.button1.Location = new System.Drawing.Point(13, 41);
              this.button1.Name = "button1";
              this.button1.Size = new System.Drawing.Size(75, 23);
              this.button1.TabIndex = 1;
              this.button1.Text = "Clear";
              this.button1.UseVisualStyleBackColor = true;
              this.button1.Click += new System.EventHandler(this.button1_Click);
              // 
              // button2
              // 
              this.button2.Location = new System.Drawing.Point(197, 41);
              this.button2.Name = "button2";
              this.button2.Size = new System.Drawing.Size(75, 23);
              this.button2.TabIndex = 2;
              this.button2.Text = "Add";
              this.button2.UseVisualStyleBackColor = true;
              this.button2.Click += new System.EventHandler(this.button2_Click);
              // 
              // dataGridView1
              // 
              this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
              this.dataGridView1.Location = new System.Drawing.Point(13, 102);
              this.dataGridView1.Name = "dataGridView1";
              this.dataGridView1.Size = new System.Drawing.Size(259, 212);
              this.dataGridView1.TabIndex = 3;
              // 
              // button3
              // 
              this.button3.Location = new System.Drawing.Point(104, 41);
              this.button3.Name = "button3";
              this.button3.Size = new System.Drawing.Size(75, 23);
              this.button3.TabIndex = 4;
              this.button3.Text = "Remove";
              this.button3.UseVisualStyleBackColor = true;
              this.button3.Click += new System.EventHandler(this.button3_Click);
              // 
              // Form1
              // 
              this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
              this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
              this.ClientSize = new System.Drawing.Size(284, 326);
              this.Controls.Add(this.button3);
              this.Controls.Add(this.dataGridView1);
              this.Controls.Add(this.button2);
              this.Controls.Add(this.button1);
              this.Name = "Form1";
              this.Text = "Form1";
              this.Load += new System.EventHandler(this.Form1_Load);
              ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
              this.ResumeLayout(false);
      
              }
      
      
      
              #endregion
      
              private System.Windows.Forms.Button button1;
              private System.Windows.Forms.Button button2;
              private System.Windows.Forms.DataGridView dataGridView1;
              private System.Windows.Forms.Button button3;
          }
      }
      

      Form1.cs

      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;
      
      namespace DataGridViewPanel
      {
          public partial class Form1 : Form
          {
              private dataBase Db = new dataBase();
              private BindingList<dataBase> DbList = new BindingList<dataBase>();
      
              public Form1()
              {
                  InitializeComponent();
              }
      
              private void Form1_Load(object sender, EventArgs e)
              {
      
                  //populate datagrid by setting datasource
                  dataGridView1.DataSource = DbList;
              }
      
              private void AddRow()
              {
                  //create a new set of data
                  dataBase db = new dataBase();
                  db.one = DateTime.Now.Day.ToString();
                  db.two = DateTime.Now.Month.ToString();
                  db.three = DateTime.Now.Year.ToString();
                  db.four = DateTime.Now.Hour.ToString();
                  db.five = DateTime.Now.Minute.ToString();
                  db.six = DateTime.Now.Second.ToString();
                  db.seven = DateTime.Now.Millisecond.ToString();
      
                  //add data to the list
                  DbList.Add(db);
      
              }
      
              private void removeRow()
              {
                  //check if cells are selected
                  if (dataGridView1.SelectedCells.Count > 0)
                  {
                      //loop while rows are selected
                      while (dataGridView1.SelectedCells.Count > 0)
                      {
                          //remove selecteed cell 0
                          DbList.RemoveAt(dataGridView1.SelectedCells[0].RowIndex);
                      }
                  }
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  //populate datagridview1 with an empty List
                  DbList.Clear();
      
              }
      
              private void button2_Click(object sender, EventArgs e)
              {
                  //add a new row to the List
                  AddRow();
              }
      
              private void button3_Click(object sender, EventArgs e)
              {
                  //remove a row from the list
                  removeRow();
              }
      
          }
      
          //custom class with string enumeration
          public class dataBase : IEnumerable<string>
          {
              public string one { get; set; }
              public string two { get; set; }
              public string three { get; set; }
              public string four { get; set; }
              public string five { get; set; }
              public string six { get; set; }
              public string seven { get; set; }
              public string eight { get; set; }
              public string nine { get; set; }
              public string ten { get; set; }
      
              public IEnumerator<string> GetEnumerator()
              {
                  yield return one;
                  yield return two;
                  yield return three;
                  yield return four;
                  yield return five;
                  yield return six;
                  yield return seven;
                  yield return eight;
                  yield return nine;
                  yield return ten;
              }
              System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
              {
                  return this.GetEnumerator();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-06
        • 2013-10-13
        • 2011-03-28
        • 2012-03-14
        • 2018-10-02
        • 1970-01-01
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        相关资源
        最近更新 更多