Csharp/CSharp Tutorial/GUI Windows Forms/DataGridView

Материал из .Net Framework эксперт
Версия от 12:15, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Calculation with DataGridView

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

   class SimpleSpreadForm : Form
   {
      public SimpleSpreadForm()
      {
         InitializeComponent();
         m_Grid.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
      }
      private void OnFormLoad(object sender, EventArgs e)
      {
         int start = (int)"A";
         for (int i = 0; i < 26; i++)
         {
            string colName = ((char)(i + start)).ToString();
            int index = m_Grid.Columns.Add(colName, colName);
            m_Grid.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            m_Grid.Columns[i].Width = 75;
         }
         for (int i = 0; i < 50; i++)
         {
            m_Grid.Rows.Add();
         }
      }
      private void OnColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
      {
         m_Grid.ClearSelection();
         foreach (DataGridViewRow row in m_Grid.Rows)
         {
            row.Cells[e.ColumnIndex].Selected = true;
         }
      }
      private void OnRowAdded(object sender, DataGridViewRowsAddedEventArgs e)
      {
         m_Grid.Rows[e.RowIndex].HeaderCell.Value = e.RowIndex.ToString();
      }
      private void OnSumCells(object sender, EventArgs e)
      {
         DataGridViewSelectedCellCollection selCells = m_Grid.SelectedCells;
         if (selCells.Count < 2)
            return;
         Dictionary<int, int> rowSum = new Dictionary<int, int>();
         Dictionary<int, int> colSum = new Dictionary<int, int>();
         foreach (DataGridViewCell cell in selCells)
         {
            if (!rowSum.ContainsKey(cell.RowIndex))
            {
               if (cell.Value != null && cell.Value.ToString() != string.Empty)
               {
                  rowSum[cell.RowIndex] = int.Parse((string)cell.Value);
               }
            }
         }
      }
      private void InitializeComponent()
      {
         this.m_Grid = new System.Windows.Forms.DataGridView();
         this.toolStrip1 = new System.Windows.Forms.ToolStrip();
         this.m_SumToolStripButton = new System.Windows.Forms.ToolStripButton();
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).BeginInit();
         this.toolStrip1.SuspendLayout();
         this.SuspendLayout();
         // 
         // m_Grid
         // 
         this.m_Grid.Dock = System.Windows.Forms.DockStyle.Fill;
         this.m_Grid.Location = new System.Drawing.Point(0, 25);
         this.m_Grid.Name = "m_Grid";
         this.m_Grid.Size = new System.Drawing.Size(727, 467);
         this.m_Grid.TabIndex = 0;
         this.m_Grid.Text = "dataGridView1";
         this.m_Grid.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.OnColumnHeaderMouseClick);
         this.m_Grid.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.OnRowAdded);
         // 
         // toolStrip1
         // 
         this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.m_SumToolStripButton});
         this.toolStrip1.Location = new System.Drawing.Point(0, 0);
         this.toolStrip1.Name = "toolStrip1";
         this.toolStrip1.Size = new System.Drawing.Size(727, 25);
         this.toolStrip1.TabIndex = 1;
         this.toolStrip1.Text = "toolStrip1";
         // 
         // m_SumToolStripButton
         // 
         this.m_SumToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
         this.m_SumToolStripButton.Name = "m_SumToolStripButton";
         this.m_SumToolStripButton.Text = "Sum";
         this.m_SumToolStripButton.Click += new System.EventHandler(this.OnSumCells);
         // 
         // SimpleSpreadForm
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(727, 492);
         this.Controls.Add(this.m_Grid);
         this.Controls.Add(this.toolStrip1);
         this.Name = "SimpleSpreadForm";
         this.Text = "Form1";
         this.Load += new System.EventHandler(this.OnFormLoad);
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).EndInit();
         this.toolStrip1.ResumeLayout(false);
         this.ResumeLayout(false);
         this.PerformLayout();
      }
      private System.Windows.Forms.DataGridView m_Grid;
      private System.Windows.Forms.ToolStrip toolStrip1;
      private System.Windows.Forms.ToolStripButton m_SumToolStripButton;
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.Run(new SimpleSpreadForm());
      }
   }

Custom Header Cells

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

   class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }
      private void OnFormLoad(object sender, EventArgs e)
      {
         m_Grid.ColumnCount = 5;
         m_Grid.Rows.Add(5);
      }
      private void OnCellPainting(object sender, DataGridViewCellPaintingEventArgs e)
      {
         if (e.RowIndex == -1) 
         {
               e.Graphics.FillRectangle(Brushes.Aqua, e.CellBounds); 
               e.Handled = true;
         }
         if (e.ColumnIndex == -1)
         {
         }
      }
      private void InitializeComponent()
      {
         this.m_Grid = new System.Windows.Forms.DataGridView();
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).BeginInit();
         this.SuspendLayout();
         // 
         this.m_Grid.Dock = System.Windows.Forms.DockStyle.Fill;
         this.m_Grid.Location = new System.Drawing.Point(0, 0);
         this.m_Grid.Name = "m_Grid";
         this.m_Grid.Size = new System.Drawing.Size(642, 347);
         this.m_Grid.TabIndex = 0;
         this.m_Grid.Text = "dataGridView1";
         this.m_Grid.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.OnCellPainting);
         // 
         // Form1
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(642, 347);
         this.Controls.Add(this.m_Grid);
         this.Name = "Form1";
         this.Text = "Form1";
         this.Load += new System.EventHandler(this.OnFormLoad);
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).EndInit();
         this.ResumeLayout(false);
      }

      private System.Windows.Forms.DataGridView m_Grid;
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.Run(new Form1());
      }
   }

Fill Columns

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
   class Form1 : Form
   {
      public Form1()
      {
         InitializeComponent();
      }
      private void InitializeComponent()
      {
         this.dataGridView1 = new System.Windows.Forms.DataGridView();
         this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
         this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
         this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
         this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
         this.Column5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
         ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
         this.SuspendLayout();
         // 
         this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2,
            this.Column3,
            this.Column4,
            this.Column5});
         this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
         this.dataGridView1.Location = new System.Drawing.Point(0, 0);
         this.dataGridView1.Name = "dataGridView1";
         this.dataGridView1.Size = new System.Drawing.Size(292, 266);
         this.dataGridView1.TabIndex = 0;
         this.dataGridView1.Text = "dataGridView1";
         // 
         this.Column1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
         this.Column1.FillWeight = 253.8071F;
         this.Column1.HeaderText = "Column1";
         this.Column1.MinimumWidth = 100;
         this.Column1.Name = "Column1";
         // 
         this.Column2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
         this.Column2.FillWeight = 61.54822F;
         this.Column2.HeaderText = "Column2";
         this.Column2.MinimumWidth = 100;
         this.Column2.Name = "Column2";
         // 
         this.Column3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
         this.Column3.FillWeight = 61.54822F;
         this.Column3.HeaderText = "Column3";
         this.Column3.MinimumWidth = 100;
         this.Column3.Name = "Column3";
         // 
         this.Column4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
         this.Column4.FillWeight = 61.54822F;
         this.Column4.HeaderText = "Column4";
         this.Column4.MinimumWidth = 100;
         this.Column4.Name = "Column4";
         // 
         // Column5
         // 
         this.Column5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
         this.Column5.FillWeight = 61.54822F;
         this.Column5.HeaderText = "Column5";
         this.Column5.Name = "Column5";
         // 
         // Form1
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(292, 266);
         this.Controls.Add(this.dataGridView1);
         this.Name = "Form1";
         this.Text = "Form1";
         ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
         this.ResumeLayout(false);
      }

      private System.Windows.Forms.DataGridView dataGridView1;
      private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
      private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
      private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
      private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
      private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
      private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
      private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
      private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
      private System.Windows.Forms.DataGridViewTextBoxColumn Column4;
      private System.Windows.Forms.DataGridViewTextBoxColumn Column5;
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.Run(new Form1());
      }
   }

Programmatic Grid

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

   class ProgrammaticGridForm: Form
   {
      public ProgrammaticGridForm()
      {
         InitializeComponent();
      }
      private void OnAddCols(object sender, EventArgs e)
      {
         m_Grid.Columns.Add("MyColumnName", "MyColumnHeaderText");
         m_Grid.Columns.Add("MyOtherColumnName", "MyOtherColumnHeaderText");
      }
      private void OnAddMore(object sender, EventArgs e)
      {
         m_Grid.ColumnCount = 5;
         m_Grid.Columns[2].Name = "Col3";
         m_Grid.Columns[2].HeaderText = "Col3";
         m_Grid.Columns[3].Name = "Col4";
         m_Grid.Columns[3].HeaderText = "Col4";
         m_Grid.Columns[4].Name = "Col5";
         m_Grid.Columns[4].HeaderText = "Col5";
      }
      private void OnRemove(object sender, EventArgs e)
      {
         m_Grid.ColumnCount = 3;
      }
      private void OnAddRows(object sender, EventArgs e)
      {
         m_Grid.Rows.Add(20);
      }
      private void OnAddHeterows(object sender, EventArgs e)
      {
         m_Grid.ColumnCount = 5;
         DataGridViewRow heterow = new DataGridViewRow();
         DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell();
         comboCell.Items.Add("Black");
         comboCell.Items.Add("White");
         comboCell.Value = "White";
         heterow.Cells.Add(comboCell);
         for (int i = 0; i < 4; i++)
         {
            heterow.Cells.Add(new DataGridViewTextBoxCell());
         }
         m_Grid.Rows.Add(heterow);
      }
      private void OnAddAnotherHeterow(object sender, EventArgs e)
      {
         DataGridViewRow heterow = new DataGridViewRow();
         heterow.CreateCells(m_Grid);
         heterow.Cells.RemoveAt(0);
         heterow.Cells.Insert(0, new DataGridViewComboBoxCell());
         m_Grid.Rows.Add(heterow);
      }
      private void InitializeComponent()
      {
         this.m_AddColsToGridButton = new System.Windows.Forms.Button();
         this.m_AddMoreColsWithColCountButton = new System.Windows.Forms.Button();
         this.m_RemoveColsButton = new System.Windows.Forms.Button();
         this.m_Grid = new System.Windows.Forms.DataGridView();
         this.m_AddRowsButton = new System.Windows.Forms.Button();
         this.m_AddHeterows = new System.Windows.Forms.Button();
         this.m_AddAnotherHeterowButton = new System.Windows.Forms.Button();
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).BeginInit();
         this.SuspendLayout();
         // 
         // m_AddColsToGridButton
         // 
         this.m_AddColsToGridButton.Location = new System.Drawing.Point(13, 13);
         this.m_AddColsToGridButton.Name = "m_AddColsToGridButton";
         this.m_AddColsToGridButton.Size = new System.Drawing.Size(131, 23);
         this.m_AddColsToGridButton.TabIndex = 0;
         this.m_AddColsToGridButton.Text = "Add Columns To Grid";
         this.m_AddColsToGridButton.Click += new System.EventHandler(this.OnAddCols);
         // 
         // m_AddMoreColsWithColCountButton
         // 
         this.m_AddMoreColsWithColCountButton.Location = new System.Drawing.Point(168, 13);
         this.m_AddMoreColsWithColCountButton.Name = "m_AddMoreColsWithColCountButton";
         this.m_AddMoreColsWithColCountButton.Size = new System.Drawing.Size(208, 23);
         this.m_AddMoreColsWithColCountButton.TabIndex = 1;
         this.m_AddMoreColsWithColCountButton.Text = "Add More Columns with ColumnCount";
         this.m_AddMoreColsWithColCountButton.Click += new System.EventHandler(this.OnAddMore);
         // 
         // m_RemoveColsButton
         // 
         this.m_RemoveColsButton.Location = new System.Drawing.Point(391, 12);
         this.m_RemoveColsButton.Name = "m_RemoveColsButton";
         this.m_RemoveColsButton.Size = new System.Drawing.Size(196, 23);
         this.m_RemoveColsButton.TabIndex = 2;
         this.m_RemoveColsButton.Text = "Remove Columns with ColumnCount";
         this.m_RemoveColsButton.Click += new System.EventHandler(this.OnRemove);
         // 
         // m_Grid
         // 
         this.m_Grid.Location = new System.Drawing.Point(12, 85);
         this.m_Grid.Name = "m_Grid";
         this.m_Grid.Size = new System.Drawing.Size(574, 265);
         this.m_Grid.TabIndex = 3;
         // 
         // m_AddRowsButton
         // 
         this.m_AddRowsButton.Location = new System.Drawing.Point(13, 43);
         this.m_AddRowsButton.Name = "m_AddRowsButton";
         this.m_AddRowsButton.Size = new System.Drawing.Size(131, 23);
         this.m_AddRowsButton.TabIndex = 4;
         this.m_AddRowsButton.Text = "Add Rows";
         this.m_AddRowsButton.Click += new System.EventHandler(this.OnAddRows);
         // 
         // m_AddHeterows
         // 
         this.m_AddHeterows.Location = new System.Drawing.Point(168, 42);
         this.m_AddHeterows.Name = "m_AddHeterows";
         this.m_AddHeterows.Size = new System.Drawing.Size(138, 23);
         this.m_AddHeterows.TabIndex = 5;
         this.m_AddHeterows.Text = "Add Heterows";
         this.m_AddHeterows.Click += new System.EventHandler(this.OnAddHeterows);
         // 
         // m_AddAnotherHeterowButton
         // 
         this.m_AddAnotherHeterowButton.Location = new System.Drawing.Point(346, 41);
         this.m_AddAnotherHeterowButton.Name = "m_AddAnotherHeterowButton";
         this.m_AddAnotherHeterowButton.Size = new System.Drawing.Size(159, 23);
         this.m_AddAnotherHeterowButton.TabIndex = 6;
         this.m_AddAnotherHeterowButton.Text = "Add Another Heterow";
         this.m_AddAnotherHeterowButton.Click += new System.EventHandler(this.OnAddAnotherHeterow);
         // 
         // ProgrammaticGridForm
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(650, 362);
         this.Controls.Add(this.m_AddAnotherHeterowButton);
         this.Controls.Add(this.m_AddHeterows);
         this.Controls.Add(this.m_AddRowsButton);
         this.Controls.Add(this.m_Grid);
         this.Controls.Add(this.m_RemoveColsButton);
         this.Controls.Add(this.m_AddMoreColsWithColCountButton);
         this.Controls.Add(this.m_AddColsToGridButton);
         this.Name = "ProgrammaticGridForm";
         this.Text = "Programmatic Grid";
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).EndInit();
         this.ResumeLayout(false);
      }

      private System.Windows.Forms.Button m_AddColsToGridButton;
      private System.Windows.Forms.Button m_AddMoreColsWithColCountButton;
      private System.Windows.Forms.Button m_RemoveColsButton;
      private System.Windows.Forms.DataGridView m_Grid;
      private System.Windows.Forms.Button m_AddRowsButton;
      private System.Windows.Forms.Button m_AddHeterows;
      private System.Windows.Forms.Button m_AddAnotherHeterowButton;
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.Run(new ProgrammaticGridForm());
      }
   }

Simple DataGridView

using System;
using System.Drawing;
using System.Windows.Forms;
class MyClass : Form
{
    [STAThread]
    public static void Main()
    {
        Application.Run(new MyClass());
    }
    public MyClass()
    {
        Text = "Simple DataGridView";
        DataGridView grid = new DataGridView();
        grid.Parent = this;
        grid.AutoSize = true;
        grid.Dock = DockStyle.Fill;
        grid.ColumnCount = 3;
        grid.Columns[0].HeaderText = "First Name";
        grid.Columns[1].HeaderText = "Last Name";
        grid.Columns[2].HeaderText = "Email Address";
    }
}

Virtual Data

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

   class VirtualModeForm : Form 
   {
      private List<DataObject> m_Data = new List<DataObject>();
      private List<bool> m_Visited = new List<bool>();
      public VirtualModeForm()
      {
         InitializeComponent();
         m_Grid.CellValueNeeded += OnCellValueNeeded;
         m_GetVisitedCountButton.Click += OnGetVisitedCount;
         InitData();
         InitGrid();
      }
      private void InitData()
      {
         for (int i = 0; i < 100; i++)
         {
            m_Visited.Add(false);
            DataObject obj = new DataObject();
            obj.Id = i;
            obj.Val = 2 * i;
            m_Data.Add(obj);
         }
      }
      private void InitGrid()
      {
         m_Grid.VirtualMode = true;
         m_Grid.ReadOnly = true;
         m_Grid.AllowUserToAddRows = false;
         m_Grid.AllowUserToDeleteRows = false;
         m_Grid.ColumnCount = 3;
         m_Grid.Rows.Add();
         m_Grid.Rows.AddCopies(0, 100);
      }
      private void OnCellValueNeeded(object sender,
         DataGridViewCellValueEventArgs e)
      {
         m_Visited[e.RowIndex] = true;
         if (e.ColumnIndex == 0)
         {
            e.Value = m_Data[e.RowIndex].Id;
         }
         else if (e.ColumnIndex == 1)
         {
            e.Value = m_Data[e.RowIndex].Val;
         }
         else if (e.ColumnIndex == 2)
         {
            Random rand = new Random();
            e.Value = rand.Next();
         }
      }
      private void OnGetVisitedCount(object sender, EventArgs e)
      {
         int count = 0;
         foreach (bool b in m_Visited)
         {
            if (b) count++;
         }
         MessageBox.Show(count.ToString());
      }
      private void InitializeComponent()
      {
         this.m_Grid = new System.Windows.Forms.DataGridView();
         this.m_GetVisitedCountButton = new System.Windows.Forms.Button();
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).BeginInit();
         this.SuspendLayout();
         // 
         // m_Grid
         // 
         this.m_Grid.Location = new System.Drawing.Point(12, 12);
         this.m_Grid.Name = "m_Grid";
         this.m_Grid.Size = new System.Drawing.Size(327, 252);
         this.m_Grid.TabIndex = 0;
         this.m_Grid.Text = "dataGridView1";
         // 
         // m_GetVisitedCountButton
         // 
         this.m_GetVisitedCountButton.Location = new System.Drawing.Point(12, 280);
         this.m_GetVisitedCountButton.Name = "m_GetVisitedCountButton";
         this.m_GetVisitedCountButton.Size = new System.Drawing.Size(231, 23);
         this.m_GetVisitedCountButton.TabIndex = 1;
         this.m_GetVisitedCountButton.Text = "Get Count of Visited Cells";
         // 
         // VirtualModeForm
         // 
         this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
         this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
         this.ClientSize = new System.Drawing.Size(365, 346);
         this.Controls.Add(this.m_GetVisitedCountButton);
         this.Controls.Add(this.m_Grid);
         this.Name = "VirtualModeForm";
         this.Text = "Form1";
         ((System.ruponentModel.ISupportInitialize)(this.m_Grid)).EndInit();
         this.ResumeLayout(false);
      }
      private System.Windows.Forms.DataGridView m_Grid;
      private System.Windows.Forms.Button m_GetVisitedCountButton;
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.Run(new VirtualModeForm());
      }
   }
   public class DataObject
   {
      private int m_Id;
      private int m_Val;
      public int Val
      {
         get { return m_Val; }
         set { m_Val = value; }
      }
      public int Id
      {
         get { return m_Id; }
         set { m_Id = value; }
      }
   }