《(学习笔记)两天进步一点点》(1)——Windows控件DGV


   

             说起来很惭愧,作为一名普通专科生,现在已经是大二了,不对、应该说现在已经大三了,按照学校的规章制度,到今年的11月份大三的学生就要离校了,接下来就要面对的实习、工作。唉,好无奈,专业课一踏糊涂、凭什么去找工作???

             所以、现在要努力了…
             《(学习笔记)两天进步一点点》从今天开始就要储蓄点点滴滴的力量、等待倾洪一泻的那一刻。

             好了闲话少说,今天就去参观一下DataGridView【Windows应用程序】控件大本营吧。

    一、总体概述
    (1)使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据。
     DataGridView其可以绑定的对象如下:

    (1)任何实现Ilist接口的类,包括一维数组。
    (2)任何实现IlistSource接口的类,包括DataTable 和 DataSet。
    (3)任何实现IBindingList接口的类,包括BindingList<T>类。
    (4)任何实现IBindSource接口的类,包括BindSource类。【BindingSource改天继续】


    (2)、DGV涉及的相关类如下:

    BindingSource 绑定的数据源

    DataGridView

    DataGridViewCell 单元格

    DataGridViewRow 行

    DataGridViewColumn列

    DataGridViewCellStyle 单元格格式


    二、常用属性(常用方法、常用事件见右)

    (1)DGV中的列类型
    当绑定 DataGridView 控件并将 AutoGenerateColumns 属性设置为 true 时,会使用与绑定数据源中包含的数据类型相应的默认列类型自动生成列。

    DataGridViewTextBoxColumn

    与基于文本的值一起使用。在绑定到数字和字符串时自动生成。
    在DataGridViewTextBoxColumn中单元格的值会自动转化成字符串,它会自动对用户输入或修改的值进行分析,以创建具有相应数据类型的单元格值。可以通过处理 DataGridView 控件的 CellFormatting 和 CellParsing 事件自定义这些转换。某一列的单元格值数据类型在该列的 ValueType 属性中指定

    DataGridViewCheckBoxColumn

    与 Boolean 和 CheckState 值一起使用。在绑定到这些类型的值时自动生成。
    DataGridViewCheckBoxColumn 与 Boolean 和 CheckState 值一起使用。Boolean 值显示为两个或三个状态的复选框,具体取决于 ThreeState 属性的值。当该列绑定到 CheckState 值时,默认情况下 ThreeState 属性的值为 true。

    DataGridViewImageColumn

    用于显示图像。在绑定到字节数组、Image 对象或 Icon 对象时自动生成。

    DataGridViewButtonColumn

    用于在单元格中显示按钮。不会在绑定时自动生成。通常用作未绑定列。

    DataGridViewComboBoxColumn

    用于在单元格中显示下拉列表。不会在绑定时自动生成。通常手动进行数据绑定。

    DataGridViewLinkColumn

    用于在单元格中显示链接。不会在绑定时自动生成。通常手动进行数据绑定。

    自定义列类型

    您可以通过继承 DataGridViewColumn 类或该类的任何一个派生类来创建自己的列类,从而提供自定义的外观、行为或寄宿控件。有关更多信息,请参见如何:通过扩展 Windows 窗体 DataGridView 控件中单元格和列的行为和外观对其进行自定义


    (2)设置 DataGridViewColumn的CellTemplate属性
     

    private void CustomizeCellsInThirdColumn()

    {

        int thirdColumn = 2;

        DataGridViewColumn column =

            dataGridView.Columns[thirdColumn];

        DataGridViewCell cell = new DataGridViewTextBoxCell();

        cell.Style.BackColor = Color.Wheat;

        column.CellTemplate = cell;

    }


    (3)设置DataGridColumn的显隐性
     

    将 DataGridViewColumn.Visible 属性设置为 false。若要隐藏数据绑定期间自动生成的 CustomerID 列,请将下面的代码示例放置在 DataBindingComplete 事件处理程序中。
    this.dataGridView1.Columns["CustomerID"].Visible = false;

    (4)移除某一列

    dataGridView1.AutoGenerateColumns = true;

    dataGridView1.DataSource = customersDataSet;

    dataGridView1.Columns.Remove("Fax");
     

    (5)设置列的显示顺序

    private void AdjustColumnOrder()

    {

        customersDataGridView.Columns["CustomerID"].Visible = false;

        customersDataGridView.Columns["ContactName"].DisplayIndex = 0;

        customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;

        customersDataGridView.Columns["City"].DisplayIndex = 2;

        customersDataGridView.Columns["Country"].DisplayIndex = 3;

        customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;

    }


    (6)冻结列

    this.dataGridView1.Columns["AddToCartButton"].Frozen = true;
     

    要实现此行为,可以冻结控件中的列。冻结一列后,其左侧(在从右到左的字符集中为右侧)的所有列也被冻结。冻结的列保持不动,而其他所有列可以滚动。

    如果允许对列进行重新排序,则将冻结的列视为一组,以区别于未冻结的列。用户可重新调整冻结和未冻结这两个组中列的位置,但不能将其中一组中的列移动到另一组。


    (7)启用列重新排序
    在 DataGridView 控件中启用列重新排序后,用户可通过使用鼠标拖动列标题的方式将列移动到新位置。在 DataGridView 控件中,DataGridView.AllowUserToOrderColumns 属性值确定用户是否能将列移动到不同的位置。

    通过编程方式启用列重新排序

    将 DataGridView.AllowUserToOrderColumns 属性设置为 true。


    (8)隐藏列标题

    将 DataGridView.ColumnHeadersVisible 属性设置为 false。


    (9)设置只读列
    dataGridView1.Columns["CompanyName"].ReadOnly = true;

    (10)防止添加和删除列行
    有时可能想要防止用户在 DataGridView 控件中输入新的数据行或删除现有行。AllowUserToAddRows 属性指示新记录的行是否呈现于控件底部,而 AllowUserToDeleteRows 属性指示是否可以移除行。下面的代码示例使用这些属性,并设置 ReadOnly 属性以使该控件完全只读。

    (11)获取或设置当前单元格
     

    注意:您不能在 Visible 属性设置为 false 的行或列中设置当前单元格。
    private void getCurrentCellButton_Click(object sender, System.EventArgs e)

    {

        string msg = String.Format("Row: {0}, Column: {1}",

            dataGridView1.CurrentCell.RowIndex,

            dataGridView1.CurrentCell.ColumnIndex);

        MessageBox.Show(msg, "Current Cell");

    }

    private void setCurrentCellButton_Click(object sender, System.EventArgs e)

    {

        // Set the current cell to the cell in column 1, Row 0.

        this.dataGridView1.CurrentCell = this.dataGridView1[1,0];

    }


    (12)在DataGridView中显示图标
     

    private void createGraphicsColumn()

    {

        Icon treeIcon = new Icon(this.GetType(), "tree.ico");

        DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();

        iconColumn.Image = treeIcon.ToBitmap();

        iconColumn.Name = "Tree";

        iconColumn.HeaderText = "Nice tree";

        dataGridView1.Columns.Insert(2, iconColumn);

    }


    (13)自定义 DataGridView中数据格式的设置

    自定义DGV中的数据格式
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    public class Form1 : Form
    {
    private DataGridView dataGridView1 = new DataGridView();
    private Bitmap highPriImage;
    private Bitmap mediumPriImage;
    private Bitmap lowPriImage;

    public Form1()
    {
    // Initialize the images.
    try
    {
    highPriImage
    = new Bitmap("highPri.bmp");
    mediumPriImage
    = new Bitmap("mediumPri.bmp");
    lowPriImage
    = new Bitmap("lowPri.bmp");
    }
    catch (ArgumentException)
    {
    MessageBox.Show(
    "The Priority column requires Bitmap images " +
    "named highPri.bmp, mediumPri.bmp, and lowPri.bmp " +
    "residing in the same directory as the executable file.");
    }

    // Initialize the DataGridView.
    dataGridView1.Dock = DockStyle.Fill;
    dataGridView1.AllowUserToAddRows
    = false;
    dataGridView1.Columns.AddRange(
    new DataGridViewTextBoxColumn(),
    new DataGridViewImageColumn());
    dataGridView1.Columns[
    0].Name = "Balance";
    dataGridView1.Columns[
    1].Name = "Priority";
    dataGridView1.Rows.Add(
    "-100", "high");
    dataGridView1.Rows.Add(
    "0", "medium");
    dataGridView1.Rows.Add(
    "100", "low");
    dataGridView1.CellFormatting
    +=
    new System.Windows.Forms.DataGridViewCellFormattingEventHandler(
    this.dataGridView1_CellFormatting);
    this.Controls.Add(dataGridView1);
    }

    // Changes how cells are displayed depending on their columns and values.
    private void dataGridView1_CellFormatting(object sender,
    System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
    {
    // Set the background to red for negative values in the Balance column.
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
    {
    Int32 intValue;
    if (Int32.TryParse((String)e.Value, out intValue) &&
    (intValue
    < 0))
    {
    e.CellStyle.BackColor
    = Color.Red;
    e.CellStyle.SelectionBackColor
    = Color.DarkRed;
    }
    }

    // Replace string values in the Priority column with images.
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Priority"))
    {
    // Ensure that the value is a string.
    String stringValue = e.Value as string;
    if (stringValue == null) return;

    // Set the cell ToolTip to the text value.
    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    cell.ToolTipText
    = stringValue;

    // Replace the string value with the image value.
    switch (stringValue)
    {
    case "high":
    e.Value
    = highPriImage;
    break;
    case "medium":
    e.Value
    = mediumPriImage;
    break;
    case "low":
    e.Value
    = lowPriImage;
    break;
    }
    }
    }

    public static void Main()
    {
    Application.Run(
    new Form1());
    }

    }


    (14)设置DGV中的数据格式
     

    设置货币和日期值的格式

    设置 DataGridViewCellStyle 的 Format 属性。下面的代码示例使用列的 DefaultCellStyle 属性设置特定列的格式。 UnitPrice 列中的值以特定于当前区域性的货币格式显示(负值用括号括起来)。 ShipDate 列中的值以特定于当前区域性的短日期格式显示。有关 Format 值的更多信息,请参见为类型设置格式。
    this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
    this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format = "d";

    自定义 null 数据库值的显示

    设置 DataGridViewCellStyle 的 NullValue 属性。下面的代码示例使用 DataGridView.DefaultCellStyle 属性在所有包含等于 DBNull.Value 的值的单元格中显示“没有项”。
    this.dataGridView1.DefaultCellStyle.NullValue = "no entry";

    在基于文本的单元格中启用换行

    将 DataGridViewCellStyle 的 WrapMode 属性设置为 DataGridViewTriState 枚举值之一。下面的代码示例使用 DataGridView.DefaultCellStyle 属性设置整个控件的换行模式。
    this.dataGridView1.DefaultCellStyle.WrapMode =
        DataGridViewTriState.True;

    指定 DataGridView 单元格的文本对齐方式

    将 DataGridViewCellStyle 的 Alignment 属性设置为 DataGridViewContentAlignment 枚举值之一。下面的代码示例使用列的 DefaultCellStyle 属性设置特定列的对齐方式。

    this.dataGridView1.Columns["CustomerName"].DefaultCellStyle
        .Alignment = DataGridViewContentAlignment.MiddleRight;

    private void SetFormatting()
    {
        this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format = "c";
        this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format = "d";
        this.dataGridView1.Columns["CustomerName"].DefaultCellStyle
            .Alignment = DataGridViewContentAlignment.MiddleRight;
        this.dataGridView1.DefaultCellStyle.NullValue = "no entry";
        this.dataGridView1.DefaultCellStyle.WrapMode =
            DataGridViewTriState.True;
    }

    (15)单元格样式
    DataGridView 控件内的每个单元格都可以有自己的样式,如文本格式、背景色、前景色和字体。但是,多个单元格通常会共享特定的样式特征。

    DefaultCellStyle

    DataGridView、DataGridViewColumn、 DataGridViewRow 和派生类

    获取或设置整个控件(包括标头单元格)、一列或一行中所有单元格使用的默认样式。

    RowsDefaultCellStyle

    DataGridView

    获取或设置控件中所有行使用的默认单元格样式。不包括标头单元格。

    AlternatingRowsDefaultCellStyle

    DataGridView

    获取或设置控件中交替行使用的默认单元格样式。用于创建帐目型的效果。

    RowHeadersDefaultCellStyle

    DataGridView

    获取或设置控件的行标头使用的默认单元格样式。如果启用视觉样式,则用当前主题进行重写。

    ColumnHeadersDefaultCellStyle

    DataGridView

    获取或设置控件的列标头使用的默认单元格样式。如果启用视觉样式,则用当前主题进行重写。

    Style

    DataGridViewCell 和派生类

    获取或设置在单元格级别指定的样式。这些样式将重写那些从较高级别继承的样式。

    InheritedStyle

    DataGridViewCell、DataGridViewRow、DataGridViewColumn 和派生类

    获取当前应用于单元格、行或列的所有样式,包括

    三、常用方法

    AutoResizeColumns

    已重载。 调整所有列的宽度以适应其单元格的内容。

    SelectAll

    选择 DataGridView 中的所有单元格。

    GetNextControl

    按照子控件的 Tab 键顺序向前或向后检索下一个控件。 (继承自 Control。)

     

    四、常用事件

    CellEnter

    在 DataGridView 控件中的当前单元格更改或者该控件接收到输入焦点时发生。

    CellFormatting

    在单元格的内容需要设置格式以便于显示时发生。

    CellLeave

    在单元格失去输入焦点因而不再是当前单元格时发生。

    CellMouseDoubleClick

    在双击 DataGridView 中的单元格时发生。

    CellMouseClick

    在用户用鼠标单击单元格中的任何位置时发生。

    CellParsing

    在单元格值已修改的情况下,当单元格退出编辑模式时发生。

    DataBindingComplete

    在数据绑定操作完成之后发生。

 

五、常用属性

 

AutoGenerateColumns

获取或设置一个值,该值指示在设置 DataSource 或 DataMember 属性时是否自动创建列。

AllowUserToAddRows

获取或设置一个值,该值指示是否向用户显示添加行的选项。

AllowUserToDeleteRows

获取或设置一个值,该值指示是否允许用户从 DataGridView 中删除行。

AllowUserToOrderColumns

获取或设置一个值,该值指示是否允许通过手动对列重新定位。

AllowUserToResizeColumns

获取或设置一个值,该值指示用户是否可以调整列的大小。

AllowUserToResizeRows

获取或设置一个值,该值指示用户是否可以调整行的大小。

Columns

获取一个包含控件中所有列的集合。

ColumnHeadersVisible

获取或设置一个值,该值指示是否显示列标题行。

CurrentCell

获取或设置当前处于活动状态的单元格。

CurrentCellAddress

获取当前处于活动状态的单元格的行索引和列索引。

CurrentRow

获取包含当前单元格的行。

DataBindings

为该控件获取数据绑定。Get

DataMember

获取或设置数据源中 DataGridView 显示其数据的列表或表的名称。

DataSource

获取或设置 DataGridView 所显示数据的数据源。

DefaultCellStyle

在未设置其他单元格样式属性的情况下,获取或设置应用于 DataGridView 中的单元格的默认单元格样式。

Rows

获取一个集合,该集合包含 DataGridView 控件中的所有行。

SelectedCells

获取用户选定的单元格的集合。

SelectedColumns

获取用户选定的列的集合。

SelectedRows

获取用户选定的行的集合。

 

 



返回导读目录,阅读更多随笔



分割线,以下为博客签名:

软件臭虫情未了
  • 编码一分钟
  • 测试十年功


随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

原文地址:https://www.cnblogs.com/08shiyan/p/1796768.html