C#.NET 或 VB.NET Windows 窗体中的 DataGridView – 技巧、窍门和常见问题

        DataGridView 控件是一个 Windows 窗体控件,它允许您自定义和编辑表格数据。它提供了许多属性、方法和事件来自定义其外观和行为。在本文中,我们将讨论一些常见问题及其解决方案。这些问题来自各种来源,包括一些新闻组、MSDN 网站以及一些由我在 MSDN 论坛上解答的问题。

技巧 1 – 填充 DataGridView

        在这个简短的代码片段中,我们将使用 LoadData() 方法填充 DataGridView。此方法使用 SqlDataAdapter 填充 DataSet。然后将 DataSet 中的“Orders”表绑定到 BindingSource 组件,这使我们能够灵活地选择/修改数据位置。

C#

public partial class Form1 : Form
    {
        private SqlDataAdapter da;
        private SqlConnection conn;
        BindingSource bsource = new BindingSource();
        DataSet ds = null;
        string sql;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btnLoad_Click(object sender, EventArgs e)
        {
            LoadData();
        }
 
        private void LoadData()
        {
string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" + "Integrated Security=SSPI;";
            conn = new SqlConnection(connectionString);
sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," + "ShipName, ShipCountry FROM Orders";
 
            da = new SqlDataAdapter(sql, conn);
            conn.Open();
            ds = new DataSet();
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);          
            da.Fill(ds, "Orders");
            bsource.DataSource = ds.Tables["Orders"];
            dgv.DataSource = bsource;          
        }
    }
    
VB.NET

Public Partial Class Form1
      Inherits Form
            Private da As SqlDataAdapter
            Private conn As SqlConnection
            Private bsource As BindingSource = New BindingSource()
            Private ds As DataSet = Nothing
            Private sql As String
 
            Public Sub New()
                  InitializeComponent()
            End Sub
 
Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As EventArgs)
                  LoadData()
            End Sub
 
            Private Sub LoadData()
Dim connectionString As String = "Data Source=localhost;Initial Catalog=Northwind;" & "Integrated Security=SSPI;"
                  conn = New SqlConnection(connectionString)
sql = "SELECT OrderID, CustomerID, EmployeeID, OrderDate, Freight," & "ShipName, ShipCountry FROM Orders"
 
                  da = New SqlDataAdapter(sql, conn)
                  conn.Open()
                  ds = New DataSet()
Dim commandBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
                  da.Fill(ds, "Orders")
                  bsource.DataSource = ds.Tables("Orders")
                  dgv.DataSource = bsource
            End Sub
End Class

技巧 2 – 更新 DataGridView 中的数据并将更改保存到数据库中

        编辑单元格中的数据后,如果您想在数据库中永久更新更改,请使用以下代码:

C#

private void btnUpdate_Click(object sender, EventArgs e)
        {
            DataTable dt = ds.Tables["Orders"];
           this.dgv.BindingContext[dt].EndCurrentEdit();
            this.da.Update(dt);
        }
        
VB.NET

Private Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Dim dt As DataTable = ds.Tables("Orders")
                  Me.dgv.BindingContext(dt).EndCurrentEdit()
                  Me.da.Update(dt)
      End Sub

技巧3 – 在 DataGridView 中删除行之前显示确认框

        处理 UserDeletingRow 事件,向用户显示确认框。如果用户确认删除,则删除该行。如果用户点击“取消”,则设置 e.cancel = true,取消行删除。

C#

private void dgv_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (!e.Row.IsNewRow)
            {
                DialogResult res = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation",
                         MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == DialogResult.No)
                    e.Cancel = true;
            }
        }
        
VB.NET

Private Sub dgv_UserDeletingRow(ByVal sender As Object, ByVal e As DataGridViewRowCancelEventArgs)
                  If (Not e.Row.IsNewRow) Then
                        Dim res As DialogResult = MessageBox.Show("Are you sure you want to delete this row?", "Delete confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        If res = DialogResult.No Then
                              e.Cancel = True
                        End If
                  End If
End Sub

技巧 4 – 如何自动调整 DataGridView 中的列宽

        下面的代码片段首先自动调整列的大小以适应其内容。然后将 AutoSizeColumnsMode 设置为“DataGridViewAutoSizeColumnsMode.AllCells”枚举值,以便在数据发生变化时自动调整列的宽度。

C#

private void btnResize_Click(object sender, EventArgs e)
        {
            dgv.AutoResizeColumns();
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
 
        }
        
VB.NET

Private Sub btnResize_Click(ByVal sender As Object, ByVal e As EventArgs)
                  dgv.AutoResizeColumns()
                  dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
 
End Sub

技巧 5 - 在 DataGridView 中选择并突出显示整行

C#

int rowToBeSelected = 3; // third row
if (dgv.Rows.Count >= rowToBeSelected)
{             
       // Since index is zero based, you have to subtract 1
        dgv.Rows[rowToBeSelected - 1].Selected = true;
}

VB.NET

Dim rowToBeSelected As Integer = 3 ' third row
If dgv.Rows.Count >= rowToBeSelected Then
         ' Since index is zero based, you have to subtract 1
            dgv.Rows(rowToBeSelected - 1).Selected = True
End If

技巧 6 - 如何以编程方式滚动到 DataGridView 中的某一行

        DataGridView 有一个名为 FirstDisplayedScrollingRowIndex 的属性,可用于以编程方式滚动到某一行。

C#

int jumpToRow = 20;
if (dgv.Rows.Count >= jumpToRow && jumpToRow >= 1)
{             
        dgv.FirstDisplayedScrollingRowIndex = jumpToRow;
        dgv.Rows[jumpToRow].Selected = true;
}
 
VB.NET

Dim jumpToRow As Integer = 20
If dgv.Rows.Count >= jumpToRow AndAlso jumpToRow >= 1 Then
            dgv.FirstDisplayedScrollingRowIndex = jumpToRow
            dgv.Rows(jumpToRow).Selected = True
End If

技巧 7 - 计算 DataGridView 中的列总数并显示在文本框中

        一个常见的需求是计算货币字段的总计并将其显示在文本框中。在下面的代码片段中,我们将计算“运费”字段的总计。然后,我们将在显示数据的同时,通过格式化结果(观察ToString( "c" ) )将数据显示在文本框中,该文本框会显示特定于文化的货币。

C#

private void btnTotal_Click(object sender, EventArgs e)
        {
            if(dgv.Rows.Count > 0)
             txtTotal.Text = Total().ToString("c");
        }
 
        private double Total()
        {
            double tot = 0;
            int i = 0;
            for (i = 0; i < dgv.Rows.Count; i++)
            {
                tot = tot + Convert.ToDouble(dgv.Rows[i].Cells["Freight"].Value);
            }
            return tot;
        }
        
VB.NET

Private Sub btnTotal_Click(ByVal sender As Object, ByVal e As EventArgs)
                  If dgv.Rows.Count > 0 Then
                   txtTotal.Text = Total().ToString("c")
                  End If
End Sub
 
Private Function Total() As Double
                  Dim tot As Double = 0
                  Dim i As Integer = 0
                  For i = 0 To dgv.Rows.Count - 1
                        tot = tot + Convert.ToDouble(dgv.Rows(i).Cells("Freight").Value)
                  Next i
                  Return tot
End Function

技巧 8 - 更改 DataGridView 中的标题名称

        如果从数据库检索的列没有有意义的名称,我们始终可以选择更改标题名称,如下段所示:

C#

private void btnChange_Click(object sender, EventArgs e)
        {
            dgv.Columns[0].HeaderText = "MyHeader1";
            dgv.Columns[1].HeaderText = "MyHeader2";
        }
 
VB.NET

Private Sub btnChange_Click(ByVal sender As Object, ByVal e As EventArgs)
                  dgv.Columns(0).HeaderText = "MyHeader1"
                  dgv.Columns(1).HeaderText = "MyHeader2"
End Sub

技巧 9 - 更改 DataGridView 中单元格、行和边框的颜色

C#

private void btnCellRow_Click(object sender, EventArgs e)
        {
            // Change ForeColor of each Cell
            this.dgv.DefaultCellStyle.ForeColor = Color.Coral;
            // Change back color of each row
            this.dgv.RowsDefaultCellStyle.BackColor = Color.AliceBlue;
            // Change GridLine Color
            this.dgv.GridColor = Color.Blue;
            // Change Grid Border Style
            this.dgv.BorderStyle = BorderStyle.Fixed3D;
        }

VB.NET

Private Sub btnCellRow_Click(ByVal sender As Object, ByVal e As EventArgs)
                  ' Change ForeColor of each Cell
                  Me.dgv.DefaultCellStyle.ForeColor = Color.Coral
                  ' Change back color of each row
                  Me.dgv.RowsDefaultCellStyle.BackColor = Color.AliceBlue
                  ' Change GridLine Color
                  Me.dgv.GridColor = Color.Blue
                  ' Change Grid Border Style
                  Me.dgv.BorderStyle = BorderStyle.Fixed3D
End Sub

技巧 10 - 隐藏 DataGridView 中的列

        如果您想根据特定条件隐藏某一列,这里有一个代码片段。

C#

private void btnHide_Click(object sender, EventArgs e)
        {
            this.dgv.Columns["EmployeeID"].Visible = false;
        }

VB.NET

Private Sub btnHide_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Me.dgv.Columns("EmployeeID").Visible = False
End Sub

技巧 11 - 处理 DataGridView 中 ComboBox 的 SelectedIndexChanged

        要处理 DataGridViewComboBox 的 SelectedIndexChanged 事件,您需要使用 DataGridView.EditingControlShowing 事件,如下所示。然后,您可以检索组合框的选定索引或选定文本。

C#

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox editingComboBox = (ComboBox)e.Control;
            if(editingComboBox != null)
                editingComboBox.SelectedIndexChanged += new System.EventHandler(this.editingComboBox_SelectedIndexChanged);
        }
        
private void editingComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            ComboBox comboBox1 = (ComboBox)sender;
            // Display index
            MessageBox.Show(comboBox1.SelectedIndex.ToString());
            // Display value
            MessageBox.Show(comboBox1.Text);
        }

VB.NET

Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
                  Dim editingComboBox As ComboBox = CType(e.Control, ComboBox)
                  If Not editingComboBox Is Nothing Then
                        AddHandler editingComboBox.SelectedIndexChanged, AddressOf editingComboBox_SelectedIndexChanged
                  End If
End Sub
 
Private Sub editingComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
                  Dim comboBox1 As ComboBox = CType(sender, ComboBox)
                  ' Display index
                  MessageBox.Show(comboBox1.SelectedIndex.ToString())
                  ' Display value
                  MessageBox.Show(comboBox1.Text)
End Sub

技巧 12 - 更改 DataGridView 中交替行的颜色

C#

private void btnAlternate_Click(object sender, EventArgs e)
        {
            this.dgv.RowsDefaultCellStyle.BackColor = Color.White;
            this.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine;
        }

VB.NET

Private Sub btnAlternate_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Me.dgv.RowsDefaultCellStyle.BackColor = Color.White
                  Me.dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.Aquamarine
End Sub

技巧 13 - 在 DataGridView 中格式化数据

        DataGridView 公开了一些属性,使您能够格式化数据,例如以特定文化的货币显示货币列或以所需的格式显示空值等等。

C#

private void btnFormat_Click(object sender, EventArgs e)
        {
            // display currency in culture-specific currency for
            this.dgv.Columns["Freight"].DefaultCellStyle.Format = "c";
            // display nulls as 'NA'
            this.dgv.DefaultCellStyle.NullValue = "NA";
        }

VB.NET

Private Sub btnFormat_Click(ByVal sender As Object, ByVal e As EventArgs)
                  ' display currency in culture-specific currency for
                  Me.dgv.Columns("Freight").DefaultCellStyle.Format = "c"
                  ' display nulls as 'NA'
                  Me.dgv.DefaultCellStyle.NullValue = "NA"
End Sub

技巧 14 – 更改 DataGridView 中的列顺序

        要更改列的顺序,只需将 DataGridView 的 DisplayIndex 属性设置为所需的值。请记住,索引从零开始。

C#

private void btnReorder_Click(object sender, EventArgs e)
        {
             dgv.Columns["CustomerID"].DisplayIndex = 5;
             dgv.Columns["OrderID"].DisplayIndex = 3;
             dgv.Columns["EmployeeID"].DisplayIndex = 1;
             dgv.Columns["OrderDate"].DisplayIndex = 2;
             dgv.Columns["Freight"].DisplayIndex = 6;
             dgv.Columns["ShipCountry"].DisplayIndex = 0;
             dgv.Columns["ShipName"].DisplayIndex = 4;
        }

VB.NET

Private Sub btnReorder_Click(ByVal sender As Object, ByVal e As EventArgs)
                   dgv.Columns("CustomerID").DisplayIndex = 5
                   dgv.Columns("OrderID").DisplayIndex = 3
                   dgv.Columns("EmployeeID").DisplayIndex = 1
                   dgv.Columns("OrderDate").DisplayIndex = 2
                   dgv.Columns("Freight").DisplayIndex = 6
                   dgv.Columns("ShipCountry").DisplayIndex = 0
                   dgv.Columns("ShipName").DisplayIndex = 4
End Sub
 
我希望这篇文章对您有用,并感谢您的阅读。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/905660.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

表记录的检索

1.select语句的语法格式 select 字段列表 from 表名 where 条件表达式 group by 分组字段 [having 条件表达式] order by 排序字段 [asc|desc];说明&#xff1a; from 子句用于指定检索的数据源 where子句用于指定记录的过滤条件 group by 子句用于对检索的数据进行分组 ha…

能源设备数据采集

在全球可持续发展目标与环境保护理念日益深入人心的时代背景下&#xff0c;有效管理和优化能源使用已成为企业实现绿色转型、提升竞争力的关键路径。能源设备数据采集系统&#xff0c;作为能源管理的核心技术支撑&#xff0c;通过对各类能源生产设备运行数据的全面收集、深度分…

【鸿蒙开发】性能优化

语言层面的优化 使用明确的数据类型&#xff0c;避免使用模糊的数据类型&#xff0c;例如ESObject。 使用AOT模式 AOT就是提前编译&#xff0c;将字节码提前编译成机器码&#xff0c;这样可以充分优化&#xff0c;从而加快执行速度。 未启用AOT时&#xff0c;一边运行一边进…

群晖NAS部署PlaylistDL音乐下载器结合cpolar搭建私有云音乐库

文章目录 前言1.关于PlaylistDL音乐下载器2.Docker部署3.PlaylistDL简单使用4.群晖安装Cpolar工具5.创建PlaylistDL音乐下载器的公网地址6.配置固定公网地址总结 前言 各位小伙伴们&#xff0c;你们是不是经常为了听几首歌而开通各种平台的VIP&#xff1f;或者为了下载无损音质…

REST架构风格介绍

一.REST&#xff08;表述性状态转移&#xff09; 1.定义 REST&#xff08;Representational State Transfer&#xff09;是由 Roy Fielding 在 2000 年提出的一种软件架构风格&#xff0c;用于设计网络应用的通信模式。它基于 HTTP 协议&#xff0c;强调通过统一的接口&#…

计算机视觉----基于锚点的车道线检测、从Line-CNN到CLRNet到CLRKDNet 本文所提算法Line-CNN 后续会更新以下全部算法

本文所提算法如下&#xff1a; 叙述按时间顺序 你也可以把本文当作快速阅读这几篇文献的一个途径 所有重要的部分我都已经标注并弄懂其原理 方便自己也是方便大家 Line-CNN&#xff1a;基于线提议单元的端到端交通线检测 摘要 交通线检测是一项基础且具有挑战性的任务。以往的…

一.android Studio开发系统应用——导入TvSettings源码

目标 最终效果如上,实现在AS中编辑源码后一键在真机中运行。达到和普通应用开发一样的调试和编码过程。这种方法可以大幅度提升开发速度,但是导入过程确实相对繁琐和消耗时间。适合需要精细或者频繁改动的系统app源码。 一、新建项目 包名:com.android.tv.settings 版本:…

20250515让飞凌的OK3588-C的核心板在Linux R4下适配以太网RTL8211F-CG为4线百兆时的接线图

20250515让飞凌的OK3588-C的核心板在Linux R4下适配以太网RTL8211F-CG为4线百兆时的接线图 2025/5/15 20:19 缘起&#xff1a;以前做的网线找不到了&#xff0c;那就再来一条吧。 引脚定义要从头来过&#xff1f;还好找到了一条。 开干&#xff01; 万用表一对/点&#xff0c;几…

【技术原理】Linux 文件时间属性详解:Access、Modify、Change 的区别与联系

在 Linux 系统中&#xff0c;每个文件都有三个核心时间属性&#xff1a;Access Time (atime)、Modify Time (mtime) 和 Change Time (ctime)。它们分别记录文件不同维度的变更信息&#xff0c;以下是具体区别与联系&#xff1a; 一、定义与触发条件 时间属性定义触发条件示例A…

乘法口诀练习神器

请你利用python语言开发一个“乘法口诀练习神器”&#xff0c;主要辅助小学生练习乘法口诀&#xff0c;主要功能如下&#xff1a; 1. 能够随机循环出10道题&#xff0c;可以是乘法或者是除法。如果是乘法&#xff0c;确保两个因数都是1-9之间的整数&#xff1b;如果是除法&…

[c语言日寄]数据结构:栈

【作者主页】siy2333 【专栏介绍】⌈c语言日寄⌋&#xff1a;这是一个专注于C语言刷题的专栏&#xff0c;精选题目&#xff0c;搭配详细题解、拓展算法。从基础语法到复杂算法&#xff0c;题目涉及的知识点全面覆盖&#xff0c;助力你系统提升。无论你是初学者&#xff0c;还是…

磁盘I/O瓶颈排查:面试通关“三部曲”心法

想象一下&#xff0c;你就是线上系统的“交通调度总指挥”&#xff0c;服务器的磁盘是所有数据进出的“核心枢纽港口”。当这个“港口”突然拥堵不堪&#xff0c;卡车&#xff08;数据请求&#xff09;排起长龙&#xff0c;进不去也出不来&#xff0c;整个系统的“物流”&#…

基于大模型预测胃穿孔预测与围手术期管理系统技术方案

目录 1. 系统架构模块2. 关键算法实现2.1 术前预测模型(Transformer多模态融合)2.2 术中实时分析(在线学习LSTM)3. 模块流程图(Mermaid)3.1 数据预处理系统3.2 术前预测系统3.3 术中实时分析系统4. 技术验证模块4.1 模型可解释性验证4.2 边缘计算部署架构1. 系统架构模块…

C++:类和对象4

一&#xff0c;日期类实现 学习建议&#xff1a; 对于计算机学习来说&#xff0c;调试十分重要&#xff0c;所以在日常学习中一定要加大代码练习&#xff0c;刷代码题和课后自己敲出课上代码例题&#xff0c;注意不要去对比正确代码或者网上找正确代码直接使用&#xff0c;一…

大数据架构选型分析

选择依据 1.业务需求与技术要求 用户需要根据自己的业务需求来选择架构&#xff0c;如果业务对于Hadoop、Spark、Strom等关键技术有强制性依赖&#xff0c;选择Lambda架构可能较为合适&#xff1b;如果处理数据偏好于流式计算&#xff0c;又依赖Flink计算引擎&#xff0c;那么…

Trae 插件 Builder 模式:从 0 到 1 开发天气查询小程序,解锁 AI 编程新体验

在软件开发领域&#xff0c;效率与创新始终是开发者追求的核心目标。Trae 插件&#xff08;原 MarsCode 编程助手&#xff09;Builder 模式的全面上线&#xff0c;无疑为开发者带来了全新的解决方案。它不仅同时支持 VS Code、JetBrains IDEs 等主流开发环境&#xff0c;还能让…

SSM项目集成redis、Linux服务器安装redis

在SSM&#xff08;Spring Spring MVC MyBatis&#xff09;项目中引入Redis主要分为以下步骤&#xff0c;确保配置正确并能在业务中灵活使用&#xff1a; 1. 添加Redis依赖​​ 在Maven的pom.xml中添加Spring Data Redis和Jedis&#xff08;或Lettuce&#xff09;依赖&#…

【Redis】压缩列表

目录 1、背景2、压缩列表【1】底层结构【2】特性【3】优缺点 1、背景 ziplist&#xff08;压缩列表&#xff09;是redis中一种特殊编码的双向链表数据结构&#xff0c;主要用于存储小型列表和哈希表。它通过紧凑的内存布局和特殊的编码方式来节省内存空间。 2、压缩列表 【1…

LocalDateTime类型的时间在前端页面不显示或者修改数据时因为LocalDateTime导致无法修改,解决方案

1.数据库中的时间数据&#xff0c;在控制台可以正常返回&#xff0c;在前端无法返回&#xff0c;即显示空白&#xff0c;如下图所示: 2.这种问题一般时由于数据库和我们实体类的名称不一致引起的&#xff0c;我们数据库一般采用_的方式命名&#xff0c;但是在Java中我们一般采用…

Spring框架核心技术深度解析:JDBC模板、模拟转账与事务管理

一、JDBC模板技术&#xff1a;简化数据库操作 在传统JDBC开发中&#xff0c;繁琐的资源管理和重复代码一直是开发者的痛点。Spring框架提供的 JDBC模板&#xff08;JdbcTemplate) 彻底改变了这一现状&#xff0c;它通过封装底层JDBC操作&#xff0c;让开发者仅需关注SQL逻辑&a…