C#开发WinForm中怎么清空DataGridView控件绑定的数据(datagridview,winform,开发技术)

时间:2024-05-05 07:41:22 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时:

1、设置DataSource为null

this.dgvDemo.DataSource=null

这样虽然可以清空DataGridView绑定的数据,但是DataGridView的列也会被删掉。

2、用DataGridView.Row.Clear()

this.dgvDemo.Rows.Clear()

使用这种方法会报错,提示“不能清除此列表”,报错信息如下:

C#开发WinForm中怎么清空DataGridView控件绑定的数据

以上两种方法都不是想要的结果。要想保持原有的列不被删除,就要清除原先绑定的DataTable中的数据,然后重新绑定DataTable

DataTabledt=this.dgvDemo.DataSourceasDataTable;dt.Rows.Clear();this.dgvDemo.DataSource=dt;

示例代码如下:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Configuration;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceDataGridViewDemo{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}stringstrCon=ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;privatevoidbtn_BindingData_Click(objectsender,EventArgse){DataTabledt=GetDataSource();this.dgvDemo.DataSource=dt;}privateDataTableGetDataSource(){DataTabledt=newDataTable();SqlConnectionconn=newSqlConnection(strCon);stringstrSQL="SELECTXIANGMUCDDMAS'项目代码',XIANGMUMCAS'项目名称',DANJIAAS'单价',SHULIANGAS'数量'FROMInPatientBillDtWHERE就诊ID='225600'";SqlCommandcmd=newSqlCommand(strSQL,conn);SqlDataAdapteradapter=newSqlDataAdapter();adapter.SelectCommand=cmd;try{conn.Open();adapter.Fill(dt);}catch(Exceptionex){MessageBox.Show(ex.Message);}finally{conn.Close();}returndt;}privatevoidbtn_Clear_Click(objectsender,EventArgse){//this.dgvDemo.DataSource=null会将DataGridView的列也删掉//this.dgvDemo.DataSource=null;//会报错:提示“不能清除此列表”//this.dgvDemo.Rows.Clear();DataTabledt=this.dgvDemo.DataSourceasDataTable;dt.Rows.Clear();this.dgvDemo.DataSource=dt;}}}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:C#开发WinForm中怎么清空DataGridView控件绑定的数据的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:怎么用Python递归式实现二叉树前序,中序,后序遍历下一篇:

10 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18