开发者

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

开发者 https://www.devze.com 2025-03-20 09:26 出处:网络 作者: 木林森先生
目录一、概要二、手动填充数据1、如何手动填充数据2、如何插入一行数据3、如何修改单元格值三、DataGridView控件绑定数据源1、概述2、将DataGridView绑定到BindingSource总结一、概要
目录
  • 一、概要
  • 二、手动填充数据
    • 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.
        DataGridViewCellSt编程yle 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(DataGridViewElementStajstes.Selected);  
    if (rowToDelete > -1)  
    {  
        this.dataGridView1.Rows.RemoveAt(rowToDelete);  
    }

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

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

    为了提高性能,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用于重新加载数据和向数据库提交更改。

    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=Truehttp://www.devze.com" 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 ijavascriptt 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)
      android      {
                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);
        }
    }
    }

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号