4 拖放
5 查看控件实时属性值
6 datagridview VirtualMode 模式
using
System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DrapDrop1
{
public partial class Form1 : Form
{
private System.Windows.Forms.ListBox ListDragSource;
private System.Windows.Forms.ListBox ListDragTarget;
private System.Windows.Forms.CheckBox UseCustomCursorsCheck;
private System.Windows.Forms.Label DropLocationLabel;
private int indexOfItemUnderMouseToDrag;
private int indexOfItemUnderMouseToDrop;
private System.Drawing.Rectangle dragBoxFromMouseDown;
private System.Drawing.Point screenOffset;
private System.Windows.Forms.Cursor MyNoDropCursor;
private System.Windows.Forms.Cursor MyNormalCursor;
public Form1()
{
InitializeComponent();
}
private void ListDragSource_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y);
if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
{
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)), dragSize);
}
else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void ListDragSource_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void ListDragSource_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Create custom cursors for the drag-and-drop operation.
try
{
MyNormalCursor = new Cursor("3dwarro.cur");
MyNoDropCursor = new Cursor("3dwno.cur");
}
catch
{
// An error occurred while attempting to load the cursors, so use
// standard cursors.
UseCustomCursorsCheck.Checked = false;
}
finally
{
// The screenOffset is used to account for any desktop bands
// that may be at the top or left side of the screen when
// determining when to cancel the drag drop operation.
screenOffset = SystemInformation.WorkingArea.Location;
// Proceed with the drag-and-drop, passing in the list item.
DragDropEffects dropEffect = ListDragSource.DoDragDrop(ListDragSource.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link);
// If the drag operation was a move then remove the item.
if (dropEffect == DragDropEffects.Move)
{
ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag);
// Selects the previous item in the list as long as the list has an item.
if (indexOfItemUnderMouseToDrag > 0)
ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag - 1;
else if (ListDragSource.Items.Count > 0)
// Selects the first item.
ListDragSource.SelectedIndex = 0;
}
// Dispose of the cursors since they are no longer needed.
if (MyNormalCursor != null)
MyNormalCursor.Dispose();
if (MyNoDropCursor != null)
MyNoDropCursor.Dispose();
}
}
}
}
private void ListDragSource_GiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs e)
{
// Use custom cursors if the check box is checked.
if (UseCustomCursorsCheck.Checked)
{
// Sets the custom cursor based upon the effect.
e.UseDefaultCursors = false;
if ((e.Effect & DragDropEffects.Move) == DragDropEffects.Move)
Cursor.Current = MyNormalCursor;
else
Cursor.Current = MyNoDropCursor;
}
}
private void ListDragTarget_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
// Determine whether string data exists in the drop data. If not, then
// the drop effect reflects that the drop cannot occur.
if (!e.Data.GetDataPresent(typeof(System.String)))
{
e.Effect = DragDropEffects.None;
DropLocationLabel.Text = "None - no string data.";
return;
}
// Set the effect based upon the KeyState.
if ((e.KeyState & (8 + 32)) == (8 + 32) &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// KeyState 8 + 32 = CTL + ALT
// Link drag-and-drop effect.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 32) == 32 &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// ALT KeyState for link.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 4) == 4 &&
(e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// SHIFT KeyState for move.
e.Effect = DragDropEffects.Move;
}
else if ((e.KeyState & 8) == 8 &&
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
// CTL KeyState for copy.
e.Effect = DragDropEffects.Copy;
}
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// By default, the drop action should be move, if allowed.
e.Effect = DragDropEffects.Move;
}
else
e.Effect = DragDropEffects.None;
// Get the index of the item the mouse is below.
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
indexOfItemUnderMouseToDrop =
ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(new Point(e.X, e.Y)));
// Updates the label text.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
{
DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
}
else
DropLocationLabel.Text = "Drops at the end.";
}
private void ListDragTarget_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
// Ensure that the list item index is contained in the data.
if (e.Data.GetDataPresent(typeof(System.String)))
{
Object item = (object)e.Data.GetData(typeof(System.String));
// Perform drag-and-drop, depending upon the effect.
if (e.Effect == DragDropEffects.Copy ||
e.Effect == DragDropEffects.Move)
{
// Insert the item.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item);
else
ListDragTarget.Items.Add(item);
}
}
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragSource_QueryContinueDrag(object sender, System.Windows.Forms.QueryContinueDragEventArgs e)
{
// Cancel the drag if the mouse moves off the form.
ListBox lb = sender as ListBox;
if (lb != null)
{
Form f = lb.FindForm();
// Cancel the drag if the mouse moves off the form. The screenOffset
// takes into account any desktop bands that may be at the top or left
// side of the screen.
if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) ||
((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) ||
((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) ||
((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom))
{
e.Action = DragAction.Cancel;
}
}
}
private void ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragTarget_DragLeave(object sender, System.EventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DrapDrop1
{
public partial class Form1 : Form
{
private System.Windows.Forms.ListBox ListDragSource;
private System.Windows.Forms.ListBox ListDragTarget;
private System.Windows.Forms.CheckBox UseCustomCursorsCheck;
private System.Windows.Forms.Label DropLocationLabel;
private int indexOfItemUnderMouseToDrag;
private int indexOfItemUnderMouseToDrop;
private System.Drawing.Rectangle dragBoxFromMouseDown;
private System.Drawing.Point screenOffset;
private System.Windows.Forms.Cursor MyNoDropCursor;
private System.Windows.Forms.Cursor MyNormalCursor;
public Form1()
{
InitializeComponent();
}
private void ListDragSource_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Get the index of the item the mouse is below.
indexOfItemUnderMouseToDrag = ListDragSource.IndexFromPoint(e.X, e.Y);
if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
{
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)), dragSize);
}
else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void ListDragSource_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void ListDragSource_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Create custom cursors for the drag-and-drop operation.
try
{
MyNormalCursor = new Cursor("3dwarro.cur");
MyNoDropCursor = new Cursor("3dwno.cur");
}
catch
{
// An error occurred while attempting to load the cursors, so use
// standard cursors.
UseCustomCursorsCheck.Checked = false;
}
finally
{
// The screenOffset is used to account for any desktop bands
// that may be at the top or left side of the screen when
// determining when to cancel the drag drop operation.
screenOffset = SystemInformation.WorkingArea.Location;
// Proceed with the drag-and-drop, passing in the list item.
DragDropEffects dropEffect = ListDragSource.DoDragDrop(ListDragSource.Items[indexOfItemUnderMouseToDrag], DragDropEffects.All | DragDropEffects.Link);
// If the drag operation was a move then remove the item.
if (dropEffect == DragDropEffects.Move)
{
ListDragSource.Items.RemoveAt(indexOfItemUnderMouseToDrag);
// Selects the previous item in the list as long as the list has an item.
if (indexOfItemUnderMouseToDrag > 0)
ListDragSource.SelectedIndex = indexOfItemUnderMouseToDrag - 1;
else if (ListDragSource.Items.Count > 0)
// Selects the first item.
ListDragSource.SelectedIndex = 0;
}
// Dispose of the cursors since they are no longer needed.
if (MyNormalCursor != null)
MyNormalCursor.Dispose();
if (MyNoDropCursor != null)
MyNoDropCursor.Dispose();
}
}
}
}
private void ListDragSource_GiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs e)
{
// Use custom cursors if the check box is checked.
if (UseCustomCursorsCheck.Checked)
{
// Sets the custom cursor based upon the effect.
e.UseDefaultCursors = false;
if ((e.Effect & DragDropEffects.Move) == DragDropEffects.Move)
Cursor.Current = MyNormalCursor;
else
Cursor.Current = MyNoDropCursor;
}
}
private void ListDragTarget_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
{
// Determine whether string data exists in the drop data. If not, then
// the drop effect reflects that the drop cannot occur.
if (!e.Data.GetDataPresent(typeof(System.String)))
{
e.Effect = DragDropEffects.None;
DropLocationLabel.Text = "None - no string data.";
return;
}
// Set the effect based upon the KeyState.
if ((e.KeyState & (8 + 32)) == (8 + 32) &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// KeyState 8 + 32 = CTL + ALT
// Link drag-and-drop effect.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 32) == 32 &&
(e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
{
// ALT KeyState for link.
e.Effect = DragDropEffects.Link;
}
else if ((e.KeyState & 4) == 4 &&
(e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// SHIFT KeyState for move.
e.Effect = DragDropEffects.Move;
}
else if ((e.KeyState & 8) == 8 &&
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
// CTL KeyState for copy.
e.Effect = DragDropEffects.Copy;
}
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
// By default, the drop action should be move, if allowed.
e.Effect = DragDropEffects.Move;
}
else
e.Effect = DragDropEffects.None;
// Get the index of the item the mouse is below.
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
indexOfItemUnderMouseToDrop =
ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(new Point(e.X, e.Y)));
// Updates the label text.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
{
DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
}
else
DropLocationLabel.Text = "Drops at the end.";
}
private void ListDragTarget_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
// Ensure that the list item index is contained in the data.
if (e.Data.GetDataPresent(typeof(System.String)))
{
Object item = (object)e.Data.GetData(typeof(System.String));
// Perform drag-and-drop, depending upon the effect.
if (e.Effect == DragDropEffects.Copy ||
e.Effect == DragDropEffects.Move)
{
// Insert the item.
if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
ListDragTarget.Items.Insert(indexOfItemUnderMouseToDrop, item);
else
ListDragTarget.Items.Add(item);
}
}
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragSource_QueryContinueDrag(object sender, System.Windows.Forms.QueryContinueDragEventArgs e)
{
// Cancel the drag if the mouse moves off the form.
ListBox lb = sender as ListBox;
if (lb != null)
{
Form f = lb.FindForm();
// Cancel the drag if the mouse moves off the form. The screenOffset
// takes into account any desktop bands that may be at the top or left
// side of the screen.
if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) ||
((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) ||
((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) ||
((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom))
{
e.Action = DragAction.Cancel;
}
}
}
private void ListDragTarget_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
private void ListDragTarget_DragLeave(object sender, System.EventArgs e)
{
// Reset the label text.
DropLocationLabel.Text = "None";
}
}
}
5 查看控件实时属性值
using
System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace SystemInfoBrowser
{
public class SystemInfoBrowserForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBox1;
public SystemInfoBrowserForm()
{
this.SuspendLayout();
InitForm();
// Add each property of the SystemInformation class to the list box.
Type t = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo[] pi = t.GetProperties();
for (int i = 0; i < pi.Length; i++)
listBox1.Items.Add(pi[i].Name);
textBox1.Text = "The SystemInformation class has " + pi.Length.ToString() + " properties. ";
// Configure the list item selected handler for the list box to invoke a
// method that displays the value of each property.
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
this.ResumeLayout(false);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Return if no list item is selected.
if (listBox1.SelectedIndex == -1) return;
// Get the property name from the list item.
string propname = listBox1.Text;
if (propname == "PowerStatus")
{
// Cycle and display the values of each property of the PowerStatus property.
textBox1.Text += " The value of the PowerStatus property is:";
Type t = typeof(System.Windows.Forms.PowerStatus);
PropertyInfo[] pi = t.GetProperties();
for (int i = 0; i < pi.Length; i++)
{
object propval = pi[i].GetValue(SystemInformation.PowerStatus, null);
textBox1.Text += " PowerStatus." + pi[i].Name + " is: " + propval.ToString();
}
}
else
{
// Display the value of the selected property of the SystemInformation type.
Type t = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo[] pi = t.GetProperties();
PropertyInfo prop = null;
for (int i = 0; i < pi.Length; i++)
if (pi[i].Name == propname)
{
prop = pi[i];
break;
}
object propval = prop.GetValue(null, null);
textBox1.Text += " The value of the " + propname + " property is: " + propval.ToString();
}
}
private void InitForm()
{
// Initialize the form settings
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.listBox1.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.listBox1.Location = new System.Drawing.Point(8, 16);
this.listBox1.Size = new System.Drawing.Size(172, 496);
this.listBox1.TabIndex = 0;
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(188, 16);
this.textBox1.Multiline = true;
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(420, 496);
this.textBox1.TabIndex = 1;
this.ClientSize = new System.Drawing.Size(616, 525);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.listBox1);
this.Text = "Select a SystemInformation property to get the value of";
}
[STAThread]
static void Main()
{
Application.Run(new SystemInfoBrowserForm());
}
}
}
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
namespace SystemInfoBrowser
{
public class SystemInfoBrowserForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.TextBox textBox1;
public SystemInfoBrowserForm()
{
this.SuspendLayout();
InitForm();
// Add each property of the SystemInformation class to the list box.
Type t = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo[] pi = t.GetProperties();
for (int i = 0; i < pi.Length; i++)
listBox1.Items.Add(pi[i].Name);
textBox1.Text = "The SystemInformation class has " + pi.Length.ToString() + " properties. ";
// Configure the list item selected handler for the list box to invoke a
// method that displays the value of each property.
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
this.ResumeLayout(false);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Return if no list item is selected.
if (listBox1.SelectedIndex == -1) return;
// Get the property name from the list item.
string propname = listBox1.Text;
if (propname == "PowerStatus")
{
// Cycle and display the values of each property of the PowerStatus property.
textBox1.Text += " The value of the PowerStatus property is:";
Type t = typeof(System.Windows.Forms.PowerStatus);
PropertyInfo[] pi = t.GetProperties();
for (int i = 0; i < pi.Length; i++)
{
object propval = pi[i].GetValue(SystemInformation.PowerStatus, null);
textBox1.Text += " PowerStatus." + pi[i].Name + " is: " + propval.ToString();
}
}
else
{
// Display the value of the selected property of the SystemInformation type.
Type t = typeof(System.Windows.Forms.SystemInformation);
PropertyInfo[] pi = t.GetProperties();
PropertyInfo prop = null;
for (int i = 0; i < pi.Length; i++)
if (pi[i].Name == propname)
{
prop = pi[i];
break;
}
object propval = prop.GetValue(null, null);
textBox1.Text += " The value of the " + propname + " property is: " + propval.ToString();
}
}
private void InitForm()
{
// Initialize the form settings
this.listBox1 = new System.Windows.Forms.ListBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.listBox1.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.listBox1.Location = new System.Drawing.Point(8, 16);
this.listBox1.Size = new System.Drawing.Size(172, 496);
this.listBox1.TabIndex = 0;
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.Location = new System.Drawing.Point(188, 16);
this.textBox1.Multiline = true;
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(420, 496);
this.textBox1.TabIndex = 1;
this.ClientSize = new System.Drawing.Size(616, 525);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.listBox1);
this.Text = "Select a SystemInformation property to get the value of";
}
[STAThread]
static void Main()
{
Application.Run(new SystemInfoBrowserForm());
}
}
}
6 datagridview VirtualMode 模式
using
System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace datagridview_virtualMode
{
public class Form1 : Form
{
private DataGridView dataGridView1 = new DataGridView();
// Declare an ArrayList to serve as the data store.
private System.Collections.ArrayList customers =
new System.Collections.ArrayList();
// Declare a Customer object to store data for a row being edited.
private Customer customerInEdit;
// Declare a variable to store the index of a row being edited.
// A value of -1 indicates that there is no row currently in edit.
private int rowInEdit = -1;
// Declare a variable to indicate the commit scope.
// Set this value to false to use cell-level commit scope.
private bool rowScopeCommit = true;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView virtual-mode demo (row-level commit scope)";
}
private void Form1_Load(object sender, EventArgs e)
{
// Enable virtual mode.
this.dataGridView1.VirtualMode = true;
// Connect the virtual-mode events to event handlers.
this.dataGridView1.CellValueNeeded += new
DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
this.dataGridView1.CellValuePushed += new
DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
this.dataGridView1.NewRowNeeded += new
DataGridViewRowEventHandler(dataGridView1_NewRowNeeded);
this.dataGridView1.RowValidated += new
DataGridViewCellEventHandler(dataGridView1_RowValidated);
this.dataGridView1.RowDirtyStateNeeded += new
QuestionEventHandler(dataGridView1_RowDirtyStateNeeded);
this.dataGridView1.CancelRowEdit += new
QuestionEventHandler(dataGridView1_CancelRowEdit);
this.dataGridView1.UserDeletingRow += new
DataGridViewRowCancelEventHandler(dataGridView1_UserDeletingRow);
// Add columns to the DataGridView.
DataGridViewTextBoxColumn companyNameColumn = new
DataGridViewTextBoxColumn();
companyNameColumn.HeaderText = "Company Name";
companyNameColumn.Name = "Company Name";
DataGridViewTextBoxColumn contactNameColumn = new
DataGridViewTextBoxColumn();
contactNameColumn.HeaderText = "Contact Name";
contactNameColumn.Name = "Contact Name";
this.dataGridView1.Columns.Add(companyNameColumn);
this.dataGridView1.Columns.Add(contactNameColumn);
this.dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
// Add some sample entries to the data store.
this.customers.Add(new Customer(
"Bon app'", "Laurence Lebihan"));
this.customers.Add(new Customer(
"Bottom-Dollar Markets", "Elizabeth Lincoln"));
this.customers.Add(new Customer(
"B's Beverages", "Victoria Ashworth"));
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 4;
}
private void dataGridView1_CellValueNeeded(object sender,
System.Windows.Forms.DataGridViewCellValueEventArgs e)
{
// If this is the row for new records, no values are needed.
if (e.RowIndex == this.dataGridView1.RowCount - 1) return;
Customer customerTmp = null;
// Store a reference to the Customer object for the row being painted.
if (e.RowIndex == rowInEdit)
{
customerTmp = this.customerInEdit;
}
else
{
customerTmp = (Customer)this.customers[e.RowIndex];
}
// Set the cell value to paint using the Customer object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
e.Value = customerTmp.CompanyName;
break;
case "Contact Name":
e.Value = customerTmp.ContactName;
break;
}
}
private void dataGridView1_CellValuePushed(object sender,
System.Windows.Forms.DataGridViewCellValueEventArgs e)
{
Customer customerTmp = null;
// Store a reference to the Customer object for the row being edited.
if (e.RowIndex < this.customers.Count)
{
// If the user is editing a new row, create a new Customer object.
if (this.customerInEdit == null)
{
this.customerInEdit = new Customer(
((Customer)this.customers[e.RowIndex]).CompanyName,
((Customer)this.customers[e.RowIndex]).ContactName);
}
customerTmp = this.customerInEdit;
this.rowInEdit = e.RowIndex;
}
else
{
customerTmp = this.customerInEdit;
}
// Set the appropriate Customer property to the cell value entered.
String newValue = e.Value as String;
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
customerTmp.CompanyName = newValue;
break;
case "Contact Name":
customerTmp.ContactName = newValue;
break;
}
}
private void dataGridView1_NewRowNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
// Create a new Customer object when the user edits
// the row for new records.
this.customerInEdit = new Customer();
this.rowInEdit = this.dataGridView1.Rows.Count - 1;
}
private void dataGridView1_RowValidated(object sender,
System.Windows.Forms.DataGridViewCellEventArgs e)
{
// Save row changes if any were made and release the edited
// Customer object if there is one.
if (e.RowIndex >= this.customers.Count &&
e.RowIndex != this.dataGridView1.Rows.Count - 1)
{
// Add the new Customer object to the data store.
this.customers.Add(this.customerInEdit);
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.customerInEdit != null &&
e.RowIndex < this.customers.Count)
{
// Save the modified Customer object in the data store.
this.customers[e.RowIndex] = this.customerInEdit;
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.dataGridView1.ContainsFocus)
{
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_RowDirtyStateNeeded(object sender,
System.Windows.Forms.QuestionEventArgs e)
{
if (!rowScopeCommit)
{
// In cell-level commit scope, indicate whether the value
// of the current cell has been modified.
e.Response = this.dataGridView1.IsCurrentCellDirty;
}
}
private void dataGridView1_CancelRowEdit(object sender,
System.Windows.Forms.QuestionEventArgs e)
{
if (this.rowInEdit == this.dataGridView1.Rows.Count - 2 &&
this.rowInEdit == this.customers.Count)
{
// If the user has canceled the edit of a newly created row,
// replace the corresponding Customer object with a new, empty one.
this.customerInEdit = new Customer();
}
else
{
// If the user has canceled the edit of an existing row,
// release the corresponding Customer object.
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_UserDeletingRow(object sender,
System.Windows.Forms.DataGridViewRowCancelEventArgs e)
{
if (e.Row.Index < this.customers.Count)
{
// If the user has deleted an existing row, remove the
// corresponding Customer object from the data store.
this.customers.RemoveAt(e.Row.Index);
}
if (e.Row.Index == this.rowInEdit)
{
// If the user has deleted a newly created row, release
// the corresponding Customer object.
this.rowInEdit = -1;
this.customerInEdit = null;
}
}
}
public class Customer
{
private String companyNameValue;
private String contactNameValue;
public Customer()
{
// Leave fields empty.
}
public Customer(String companyName, String contactName)
{
companyNameValue = companyName;
contactNameValue = contactName;
}
public String CompanyName
{
get
{
return companyNameValue;
}
set
{
companyNameValue = value;
}
}
public String ContactName
{
get
{
return contactNameValue;
}
set
{
contactNameValue = value;
}
}
}
}
using System.Collections.Generic;
using System.Windows.Forms;
namespace datagridview_virtualMode
{
public class Form1 : Form
{
private DataGridView dataGridView1 = new DataGridView();
// Declare an ArrayList to serve as the data store.
private System.Collections.ArrayList customers =
new System.Collections.ArrayList();
// Declare a Customer object to store data for a row being edited.
private Customer customerInEdit;
// Declare a variable to store the index of a row being edited.
// A value of -1 indicates that there is no row currently in edit.
private int rowInEdit = -1;
// Declare a variable to indicate the commit scope.
// Set this value to false to use cell-level commit scope.
private bool rowScopeCommit = true;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView virtual-mode demo (row-level commit scope)";
}
private void Form1_Load(object sender, EventArgs e)
{
// Enable virtual mode.
this.dataGridView1.VirtualMode = true;
// Connect the virtual-mode events to event handlers.
this.dataGridView1.CellValueNeeded += new
DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
this.dataGridView1.CellValuePushed += new
DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
this.dataGridView1.NewRowNeeded += new
DataGridViewRowEventHandler(dataGridView1_NewRowNeeded);
this.dataGridView1.RowValidated += new
DataGridViewCellEventHandler(dataGridView1_RowValidated);
this.dataGridView1.RowDirtyStateNeeded += new
QuestionEventHandler(dataGridView1_RowDirtyStateNeeded);
this.dataGridView1.CancelRowEdit += new
QuestionEventHandler(dataGridView1_CancelRowEdit);
this.dataGridView1.UserDeletingRow += new
DataGridViewRowCancelEventHandler(dataGridView1_UserDeletingRow);
// Add columns to the DataGridView.
DataGridViewTextBoxColumn companyNameColumn = new
DataGridViewTextBoxColumn();
companyNameColumn.HeaderText = "Company Name";
companyNameColumn.Name = "Company Name";
DataGridViewTextBoxColumn contactNameColumn = new
DataGridViewTextBoxColumn();
contactNameColumn.HeaderText = "Contact Name";
contactNameColumn.Name = "Contact Name";
this.dataGridView1.Columns.Add(companyNameColumn);
this.dataGridView1.Columns.Add(contactNameColumn);
this.dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
// Add some sample entries to the data store.
this.customers.Add(new Customer(
"Bon app'", "Laurence Lebihan"));
this.customers.Add(new Customer(
"Bottom-Dollar Markets", "Elizabeth Lincoln"));
this.customers.Add(new Customer(
"B's Beverages", "Victoria Ashworth"));
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 4;
}
private void dataGridView1_CellValueNeeded(object sender,
System.Windows.Forms.DataGridViewCellValueEventArgs e)
{
// If this is the row for new records, no values are needed.
if (e.RowIndex == this.dataGridView1.RowCount - 1) return;
Customer customerTmp = null;
// Store a reference to the Customer object for the row being painted.
if (e.RowIndex == rowInEdit)
{
customerTmp = this.customerInEdit;
}
else
{
customerTmp = (Customer)this.customers[e.RowIndex];
}
// Set the cell value to paint using the Customer object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
e.Value = customerTmp.CompanyName;
break;
case "Contact Name":
e.Value = customerTmp.ContactName;
break;
}
}
private void dataGridView1_CellValuePushed(object sender,
System.Windows.Forms.DataGridViewCellValueEventArgs e)
{
Customer customerTmp = null;
// Store a reference to the Customer object for the row being edited.
if (e.RowIndex < this.customers.Count)
{
// If the user is editing a new row, create a new Customer object.
if (this.customerInEdit == null)
{
this.customerInEdit = new Customer(
((Customer)this.customers[e.RowIndex]).CompanyName,
((Customer)this.customers[e.RowIndex]).ContactName);
}
customerTmp = this.customerInEdit;
this.rowInEdit = e.RowIndex;
}
else
{
customerTmp = this.customerInEdit;
}
// Set the appropriate Customer property to the cell value entered.
String newValue = e.Value as String;
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
customerTmp.CompanyName = newValue;
break;
case "Contact Name":
customerTmp.ContactName = newValue;
break;
}
}
private void dataGridView1_NewRowNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
// Create a new Customer object when the user edits
// the row for new records.
this.customerInEdit = new Customer();
this.rowInEdit = this.dataGridView1.Rows.Count - 1;
}
private void dataGridView1_RowValidated(object sender,
System.Windows.Forms.DataGridViewCellEventArgs e)
{
// Save row changes if any were made and release the edited
// Customer object if there is one.
if (e.RowIndex >= this.customers.Count &&
e.RowIndex != this.dataGridView1.Rows.Count - 1)
{
// Add the new Customer object to the data store.
this.customers.Add(this.customerInEdit);
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.customerInEdit != null &&
e.RowIndex < this.customers.Count)
{
// Save the modified Customer object in the data store.
this.customers[e.RowIndex] = this.customerInEdit;
this.customerInEdit = null;
this.rowInEdit = -1;
}
else if (this.dataGridView1.ContainsFocus)
{
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_RowDirtyStateNeeded(object sender,
System.Windows.Forms.QuestionEventArgs e)
{
if (!rowScopeCommit)
{
// In cell-level commit scope, indicate whether the value
// of the current cell has been modified.
e.Response = this.dataGridView1.IsCurrentCellDirty;
}
}
private void dataGridView1_CancelRowEdit(object sender,
System.Windows.Forms.QuestionEventArgs e)
{
if (this.rowInEdit == this.dataGridView1.Rows.Count - 2 &&
this.rowInEdit == this.customers.Count)
{
// If the user has canceled the edit of a newly created row,
// replace the corresponding Customer object with a new, empty one.
this.customerInEdit = new Customer();
}
else
{
// If the user has canceled the edit of an existing row,
// release the corresponding Customer object.
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
private void dataGridView1_UserDeletingRow(object sender,
System.Windows.Forms.DataGridViewRowCancelEventArgs e)
{
if (e.Row.Index < this.customers.Count)
{
// If the user has deleted an existing row, remove the
// corresponding Customer object from the data store.
this.customers.RemoveAt(e.Row.Index);
}
if (e.Row.Index == this.rowInEdit)
{
// If the user has deleted a newly created row, release
// the corresponding Customer object.
this.rowInEdit = -1;
this.customerInEdit = null;
}
}
}
public class Customer
{
private String companyNameValue;
private String contactNameValue;
public Customer()
{
// Leave fields empty.
}
public Customer(String companyName, String contactName)
{
companyNameValue = companyName;
contactNameValue = contactName;
}
public String CompanyName
{
get
{
return companyNameValue;
}
set
{
companyNameValue = value;
}
}
public String ContactName
{
get
{
return contactNameValue;
}
set
{
contactNameValue = value;
}
}
}
}