C#开发WinForm中怎么清空DataGridView控件绑定的数据
导读:本文共1375字符,通常情况下阅读需要5分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时:1、设置DataSource为nullthis.dgvDemo.DataSource=null这样虽然可以清空DataGridView绑定的数据,但是DataGridView的列也会被删掉。2、用DataGridView.Row.Clear()this.... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。使用DataGridView控件绑定数据后有时需要清空绑定的数据,在清除DataGridView绑定的数据时:
1、设置DataSource为null
this.dgvDemo.DataSource=null
这样虽然可以清空DataGridView绑定的数据,但是DataGridView的列也会被删掉。
2、用DataGridView.Row.Clear()
this.dgvDemo.Rows.Clear()
使用这种方法会报错,提示“不能清除此列表”,报错信息如下:
以上两种方法都不是想要的结果。要想保持原有的列不被删除,就要清除原先绑定的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控件绑定的数据的详细内容,希望对您有所帮助,信息来源于网络。