• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    C#表格开发之DataGridView控件详解

    发布者: 404号房间 | 发布时间: 2025-6-20 09:00| 查看数: 38| 评论数: 0|帖子模式

    一、概要

    使用DataGridView控件,您可以显示和编辑来自许多不同类型数据源的表格数据。
    DataGridView控件为显示数据提供了一个可定制的表格。DataGridView类允许通过使用DefaultCellStyle、ColumnHeadersDefaultCellStyle、CellBorderStyle和GridColor等属性来定制单元格、行、列和边框。
    无论有或没有底层数据源的数据,你都可以在使用DataGridView控件显示出你所期望显示的数据。
    如果没有指定的数据源,你可以创建包含数据的rows和coumns,并使用DataGridView类里的RowsColumns属性将它们直接添加到DataGridView控件中。您可以使用Rows集合来访问DataGridViewRow对象,也可以使用DataGridViewRow.Cell属性直接读取或写入单元格值。另外,还有 Item[] 索引器提供了对单元格的直接访问。
    您可以设置DataSourceDataMember属性,以将DataGridView控件绑定到数据源并自动向其填充数据,这种方法可以做为手动填充数据的替代方法。但是前提条件是必须有指定的数据源。
    当处理大量数据时,可以将VirtualMode属性设置为true,以显示可用数据的子集。虚拟模式需要实现数据缓存,从中填充DataGridView控件。

    二、手动填充数据


    1、如何手动填充数据

    下面的代码示例演示如何创建一个未绑定的DataGridView;设置ColumnHeadersVisibleColumnHeadersDefaultCellStyleColumnCount属性;并使用Rows属性和Columns属性。
    它还演示了如何使用AutoResizeColumnHeadersHeight()AutoResizeRows()方法的一个版本,来适当地调整列标头和行的大小。
    要运行此示例,请将以下代码粘贴到包含名为dataGridView1的DataGridView和名为Button1的button的表格中,然后从表格的构造函数或Load事件处理程序调用InitializeDataGridView()方法。确保所有事件都与其事件处理程序相连接。
    1. public Form1()
    2. {
    3.         InitializeComponent();
    4.         InitializeDataGridView();

    5. }
    6. private void InitializeDataGridView()
    7. {
    8.     // Create an unbound DataGridView by declaring a column count.
    9.     dataGridView1.ColumnCount = 4;
    10.     dataGridView1.ColumnHeadersVisible = true;

    11.     // Set the column header style.
    12.     DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

    13.     columnHeaderStyle.BackColor = Color.Beige;
    14.     columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold);
    15.     dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

    16.     // Set the column header names.
    17.     dataGridView1.Columns[0].Name = "Recipe";
    18.     dataGridView1.Columns[1].Name = "Category";
    19.     dataGridView1.Columns[2].Name = "Main Ingredients";
    20.     dataGridView1.Columns[3].Name = "Rating";

    21.     // Populate the rows.
    22.     string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef", "**" };
    23.     string[] row2 = new string[] { "Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****" };
    24.     string[] row3 = new string[] { "Orange-Salsa Pork Chops", "Main Dish", "pork chops, salsa, orange juice", "****" };
    25.     string[] row4 = new string[] { "Black Bean and Rice Salad", "Salad", "black beans, brown rice", "****" };
    26.     string[] row5 = new string[] { "Chocolate Cheesecake", "Dessert",  "cream cheese", "***" };
    27.     string[] row6 = new string[] { "Black Bean Dip", "Appetizer",  "black beans, sour cream", "***" };
    28.     object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

    29.     foreach (string[] rowArray in rows)
    30.     {
    31.         dataGridView1.Rows.Add(rowArray);
    32.     }
    33. }

    34. private void button1_Click(object sender, System.EventArgs e)
    35. {
    36.     // Resize the height of the column headers.
    37.     dataGridView1.AutoResizeColumnHeadersHeight();

    38.     // Resize all the row heights to fit the contents of all non-header cells.
    39.     dataGridView1.AutoResizeRows( DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
    40. }

    41. private void InitializeContextMenu()
    42. {
    43.     // Create the menu item.
    44.     ToolStripMenuItem getRecipe = new ToolStripMenuItem("Search for recipe", null,
    45.         new System.EventHandler(ShortcutMenuClick));

    46.     // Add the menu item to the shortcut menu.
    47.     ContextMenuStrip recipeMenu = new ContextMenuStrip();
    48.     recipeMenu.Items.Add(getRecipe);

    49.     // Set the shortcut menu for the first column.
    50.     dataGridView1.Columns[0].ContextMenuStrip = recipeMenu;
    51.     dataGridView1.MouseDown += new MouseEventHandler(dataGridView1_MouseDown);
    52. }

    53. private DataGridViewCell clickedCell;

    54. //当鼠标指针位于控件上并按下鼠标键时发生。
    55. private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    56. {
    57. // If the user right-clicks a cell, store it for use by the shortcut menu.
    58.     if (e.Button == MouseButtons.Right)
    59.     {
    60.         DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);
    61.         if (hit.Type == DataGridViewHitTestType.Cell)
    62.         {
    63.             clickedCell =
    64.                 dataGridView1.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
    65.         }
    66.     }
    67. }

    68. private void ShortcutMenuClick(object sender, System.EventArgs e)
    69. {
    70.     if (clickedCell != null)
    71.     {
    72.         //Retrieve the recipe name.
    73.         string recipeName = (string)clickedCell.Value;

    74.         //Search for the recipe.
    75.         System.Diagnostics.Process.Start(
    76.             "http://search.msn.com/results.aspx?q=" + recipeName);
    77.             //null);
    78.     }
    79. }
    复制代码
    上述代码中,先创建数个字符串数组,数组的元素数量等于dataGridView1的列的数量。然后在循环中,调用dataGridView1.Rows.Add(rowArray);方法,将数组元素填充进dataGridView1的某行中。

    2、如何插入一行数据

    如果你想要向DataGridView表格中插入一行数据,可以使用下面代码:
    1. this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");
    复制代码
    该行代码表示向dataGridView1中插入一条数据到第0行。
    如果你想要插入一行空的单元格,可以使用下列代码:
    1. this.dataGridView1.Rows.Insert(0, "", "", "", "");
    复制代码
    Rows属性,不但包括值,还包括样式信息。因此,你可以根据已设置样式的现有行添加或插入行,这时,你可以使用AddCopy()、AddCopies()、InsertCopy()InsertCopies()方法来做到这一点。
    你还可以使用Rows集合修改控件中的值或删除行。无论控件是否绑定到外部数据源,都可以修改值或删除行。如果存在数据源,则直接对数据源进行更改。但是,您可能仍然需要将数据源更新推送到远程数据库。

    3、如何修改单元格值

    下面的示例向您展示如何以编程方式修改单元格值。
    1. // Modify the value in the first cell of the second row.  
    2. this.dataGridView1.Rows[1].Cells[0].Value = "new value";  

    3. // The previous line is equivalent to the following line.  
    4. this.dataGridView1[0, 1].Value = "new value";
    复制代码
    除了标准集合功能之外,您还可以使用Rows集合来检索行信息。例如,你可以使用GetRowState()方法确定特定行的状态,也可以使用GetRowCount()GetRowsHeight()方法来确定特定状态下的行数或行的组合高度。
    如果你要检索具有特定状态的行索引,可以使用GetFirstRow()GetLastRow()GetNextRow()GetPreviousRow()方法。
    下面的示例向您展示如何检索第一个选定行的索引,然后使用它以编程方式删除该行。
    1. Int32 rowToDelete = this.dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);  
    2. if (rowToDelete > -1)  
    3. {  
    4.     this.dataGridView1.Rows.RemoveAt(rowToDelete);  
    5. }
    复制代码
    上述代码,是在选定某些行的时候,删除选中行里的第一行。注意:选中行时是包含行头在内。如下图所示 :

    为了提高性能,Rows属性返回的DataGridViewRowCollection可以包括共享行和非共享行。共享行共享内存,以减少大型记录集的成本。如果您的记录集非常大,那么在访问rows属性时应该小心地尽可能多地保持行共享。

    三、DataGridView控件绑定数据源


    1、概述

    DataGridView控件支持标准的Windows窗体数据绑定模型,因此它可以绑定到各种数据源。通常,您绑定到管理与数据源交互的BindingSource。BindingSource可以是任何Windows窗体数据源,这在选择或修改数据位置时为您提供了极大的灵活性。
    将数据绑定到DataGridView控件是直接和直观的,在许多情况下,它就像设置DataSource属性一样简单。当绑定到包含多个列表或表的数据源时,请将DataMember属性设置为指定要绑定到的列表或表的字符串。
    DataGridView控件支持标准的Windows窗体数据绑定模型,因此它将绑定到以下列表中描述的类的实例:

    • 实现IList接口的任何类,包括一维数组。
    • 实现IListSource接口的任何类,例如DataTable和DataSet类。
    • 任何实现IBindingList接口的类,例如BindingList<T>类。
    • 任何实现IBindingListView接口的类,比如BindingSource类。
    DataGridView控件支持将数据绑定到这些接口返回的对象的公共属性,或者绑定到ICustomTypeDescriptor接口返回的属性集合(如果在返回的对象上实现的话)。
    通常,您将DataGridView绑定到一个BindingSource组件,并将BindingSource组件绑定到另一个数据源,或者用业务对象填充它。
    BindingSource组件是首选的数据源,因为它可以绑定到各种各样的数据源,并且可以自动解决许多数据绑定问题。

    2、将DataGridView绑定到BindingSource

    连接DataGridView控件到data的步骤:

    • 实现一个方法来处理检索数据的细节。下面的代码示例实现了一个GetData方法,该方法初始化一个SqlDataAdapter,并使用它来填充一个DataTable。然后将DataTable绑定到BindingSource。
    • 在Form的Load事件处理程序中,将DataGridView控件绑定到BindingSource,并调用GetData方法来检索数据。
    用您的Northwind SQL Server示例数据库连接的值填充示例中的connectionString变量。Windows身份验证,也称为集成安全,是一种比在连接字符串中存储密码更安全的连接数据库的方式。
    下列完整的代码演示了从数据库中检索数据,并填充到Windows窗体中的DataGridView控件。Form还有一些button用于重新加载数据和向数据库提交更改。
    1. using System;
    2. using System.Data;
    3. using System.Data.SqlClient;
    4. using System.Globalization;
    5. using System.Windows.Forms;

    6. namespace WindowsFormsApp
    7. {
    8.         public class BindSourceForm1 : Form
    9. {
    10.     private DataGridView dataGridView1 = new DataGridView();
    11.     private BindingSource bindingSource1 = new BindingSource();
    12.     private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    13.     private Button reloadButton = new Button();
    14.     private Button submitButton = new Button();


    15.     // Initialize the form.
    16.     public Form1()
    17.     {
    18.                 InitializeComponent();
    19.                
    20.         dataGridView1.Dock = DockStyle.Fill;

    21.         reloadButton.Text = "Reload";
    22.         submitButton.Text = "Submit";
    23.         reloadButton.Click += new EventHandler(ReloadButton_Click);
    24.         submitButton.Click += new EventHandler(SubmitButton_Click);

    25.         FlowLayoutPanel panel = new FlowLayoutPanel
    26.         {
    27.             Dock = DockStyle.Top,
    28.             AutoSize = true
    29.         };
    30.         panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

    31.         Controls.AddRange(new Control[] { dataGridView1, panel });
    32.         Load += new EventHandler(Form1_Load);
    33.         Text = "DataGridView data binding and updating demo";
    34.     }

    35.     private void GetData(string selectCommand)
    36.     {
    37.         try
    38.         {
    39.             // Specify a connection string.
    40.             // Replace <SQL Server> with the SQL Server for your Northwind sample database.
    41.             // Replace "Integrated Security=True" with user login information if necessary.
    42.             String connectionString =
    43.                 "Data Source=(local);Initial Catalog=Northwind;" +
    44.                 "Integrated Security=True";

    45.             // Create a new data adapter based on the specified query.
    46.             dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

    47.             // Create a command builder to generate SQL update, insert, and
    48.             // delete commands based on selectCommand.
    49.             SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

    50.             // Populate a new data table and bind it to the BindingSource.
    51.             DataTable table = new DataTable
    52.             {
    53.                 Locale = CultureInfo.InvariantCulture
    54.             };
    55.             dataAdapter.Fill(table);
    56.             bindingSource1.DataSource = table;

    57.             // Resize the DataGridView columns to fit the newly loaded content.
    58.             dataGridView1.AutoResizeColumns(
    59.                 DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
    60.         }
    61.         catch (SqlException)
    62.         {
    63.             MessageBox.Show("To run this example, replace the value of the " +
    64.                 "connectionString variable with a connection string that is " +
    65.                 "valid for your system.");
    66.         }
    67.     }

    68.     private void Form1_Load(object sender, EventArgs e)
    69.     {
    70.         // Bind the DataGridView to the BindingSource
    71.         // and load the data from the database.
    72.         dataGridView1.DataSource = bindingSource1;
    73.         GetData("select * from Customers");
    74.     }

    75.     private void ReloadButton_Click(object sender, EventArgs e)
    76.     {
    77.         // Reload the data from the database.
    78.         GetData(dataAdapter.SelectCommand.CommandText);
    79.     }

    80.     private void SubmitButton_Click(object sender, EventArgs e)
    81.     {
    82.         // Update the database with changes.
    83.         dataAdapter.Update((DataTable)bindingSource1.DataSource);
    84.     }
    85. }
    86. }
    复制代码
    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    来源:https://www.jb51.net/database/3332490hx.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表