C#——表格开发之DataGridView控件_c# datagridview-程序员宅基地

技术标签: C#  c#  DataGridView  开发语言  

目录

一、概要

二、手动填充数据

1、如何手动填充数据

2、如何插入一行数据

3、如何修改单元格值

三、DataGridView控件绑定数据源

1、概述

2、将DataGridView绑定到BindingSource


一、概要

使用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()方法。确保所有事件都与其事件处理程序相连接。

public Form1()
{
	InitializeComponent();
	InitializeDataGridView();

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

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

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

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

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

    foreach (string[] rowArray in rows)
    {
        dataGridView1.Rows.Add(rowArray);
    }
}

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

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

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

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

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

private DataGridViewCell clickedCell;

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

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

        //Search for the recipe.
        System.Diagnostics.Process.Start(
            "http://search.msn.com/results.aspx?q=" + recipeName);
            //null);
    }
}

上述代码中,先创建数个字符串数组,数组的元素数量等于dataGridView1的列的数量。然后在循环中,调用dataGridView1.Rows.Add(rowArray);方法,将数组元素填充进dataGridView1的某行中。

2、如何插入一行数据

如果你想要向DataGridView表格中插入一行数据,可以使用下面代码:

this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");

该行代码表示向dataGridView1中插入一条数据到第0行。

如果你想要插入一行空的单元格,可以使用下列代码:

this.dataGridView1.Rows.Insert(0, "", "", "", "");

Rows属性,不但包括值,还包括样式信息。因此,你可以根据已设置样式的现有行添加或插入行,这时,你可以使用AddCopy()、AddCopies()、InsertCopy()InsertCopies()方法来做到这一点。

你还可以使用Rows集合修改控件中的值或删除行。无论控件是否绑定到外部数据源,都可以修改值或删除行。如果存在数据源,则直接对数据源进行更改。但是,您可能仍然需要将数据源更新推送到远程数据库。

3、如何修改单元格值

下面的示例向您展示如何以编程方式修改单元格值。

// Modify the value in the first cell of the second row.  
this.dataGridView1.Rows[1].Cells[0].Value = "new value";  

// The previous line is equivalent to the following line.  
this.dataGridView1[0, 1].Value = "new value";

除了标准集合功能之外,您还可以使用Rows集合来检索行信息。例如,你可以使用GetRowState()方法确定特定行的状态,也可以使用GetRowCount()GetRowsHeight()方法来确定特定状态下的行数或行的组合高度。

如果你要检索具有特定状态的行索引,可以使用GetFirstRow()GetLastRow()GetNextRow()GetPreviousRow()方法。

下面的示例向您展示如何检索第一个选定行的索引,然后使用它以编程方式删除该行。

Int32 rowToDelete = this.dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);  
if (rowToDelete > -1)  
{  
    this.dataGridView1.Rows.RemoveAt(rowToDelete);  
}

上述代码,是在选定某些行的时候,删除选中行里的第一行。注意:选中行时是包含行头在内。如下图所示 :

为了提高性能,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的步骤:

  1. 实现一个方法来处理检索数据的细节。下面的代码示例实现了一个GetData方法,该方法初始化一个SqlDataAdapter,并使用它来填充一个DataTable。然后将DataTable绑定到BindingSource。
  2. 在Form的Load事件处理程序中,将DataGridView控件绑定到BindingSource,并调用GetData方法来检索数据。

用您的Northwind SQL Server示例数据库连接的值填充示例中的connectionString变量。Windows身份验证,也称为集成安全,是一种比在连接字符串中存储密码更安全的连接数据库的方式。

下列完整的代码演示了从数据库中检索数据,并填充到Windows窗体中的DataGridView控件。Form还有一些button用于重新加载数据和向数据库提交更改。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;

namespace WindowsFormsApp
{
	public class BindSourceForm1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bindingSource1 = new BindingSource();
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    private Button reloadButton = new Button();
    private Button submitButton = new Button();


    // Initialize the form.
    public Form1()
    {
		InitializeComponent();
		
        dataGridView1.Dock = DockStyle.Fill;

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

        FlowLayoutPanel panel = new FlowLayoutPanel
        {
            Dock = DockStyle.Top,
            AutoSize = true
        };
        panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

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

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

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

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

            // Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable
            {
                Locale = CultureInfo.InvariantCulture
            };
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;

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

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

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

    private void SubmitButton_Click(object sender, EventArgs e)
    {
        // Update the database with changes.
        dataAdapter.Update((DataTable)bindingSource1.DataSource);
    }
}
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_59555766/article/details/132723317

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签