C#开发WinForm中怎么清空DataGridView控件绑定的数据
发表于:2024-09-25 作者:千家信息网编辑
千家信息网最后更新 2024年09月25日,本文小编为大家详细介绍"C#开发WinForm中怎么清空DataGridView控件绑定的数据",内容详细,步骤清晰,细节处理妥当,希望这篇"C#开发WinForm中怎么清空DataGridView控
千家信息网最后更新 2024年09月25日C#开发WinForm中怎么清空DataGridView控件绑定的数据
本文小编为大家详细介绍"C#开发WinForm中怎么清空DataGridView控件绑定的数据",内容详细,步骤清晰,细节处理妥当,希望这篇"C#开发WinForm中怎么清空DataGridView控件绑定的数据"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时:
1、设置DataSource为null
this.dgvDemo.DataSource = null
这样虽然可以清空DataGridView绑定的数据,但是DataGridView的列也会被删掉。
2、用DataGridView.Row.Clear()
this.dgvDemo.Rows.Clear()
使用这种方法会报错,提示"不能清除此列表",报错信息如下:
以上两种方法都不是想要的结果。要想保持原有的列不被删除,就要清除原先绑定的DataTable中的数据,然后重新绑定DataTable
DataTable dt = this.dgvDemo.DataSource as DataTable;dt.Rows.Clear();this.dgvDemo.DataSource = dt;
示例代码如下:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace DataGridViewDemo{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; private void btn_BindingData_Click(object sender, EventArgs e) { DataTable dt = GetDataSource(); this.dgvDemo.DataSource = dt; } private DataTable GetDataSource() { DataTable dt = new DataTable(); SqlConnection conn = new SqlConnection(strCon); string strSQL = "SELECT XIANGMUCDDM AS '项目代码',XIANGMUMC AS '项目名称', DANJIA AS '单价',SHULIANG AS '数量' FROM InPatientBillDt WHERE 就诊ID='225600'"; SqlCommand cmd = new SqlCommand(strSQL, conn); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; try { conn.Open(); adapter.Fill(dt); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { conn.Close(); } return dt; } private void btn_Clear_Click(object sender, EventArgs e) { // this.dgvDemo.DataSource = null会将DataGridView的列也删掉 //this.dgvDemo.DataSource = null; // 会报错:提示"不能清除此列表" //this.dgvDemo.Rows.Clear(); DataTable dt = this.dgvDemo.DataSource as DataTable; dt.Rows.Clear(); this.dgvDemo.DataSource = dt; } }}
读到这里,这篇"C#开发WinForm中怎么清空DataGridView控件绑定的数据"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
数据
控件
C#
开发
文章
代码
内容
方法
项目
会报
提示
妥当
信息
单价
名称
思路
数量
新知
更多
步骤
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
网络安全防护技术视频
海淀区口碑好的网络技术信息推荐
网络安全中职演讲稿
软件开发和云计算哪个专业好
达梦数据库 怎么样
网络安全防范诗歌
3d打印软件开发语言
后端开发和软件开发一样吗
移动应用软件开发的未来
浙江数据网络技术
软件开发和网站建设那个好
宁海应用软件开发流程
c 如何与数据库通信
联想sr650服务器
网络安全危害国家安全案例
深圳这边网络安全公司
软件开发在线学
项目不放在服务器上能行吗
搭建数据库需要什么设备
网络安全是弊
网络数据库的要求
sql 查询数据库表行数
中国知网数据库笔试题
ios重复恢复数据库
服务器连接电视怎么设置
网站导航软件开发
计算机网络安全维护包含哪些
东莞餐饮软件开发程序
华为服务器按开机键没反应
计算机网络技术基础实体