C#開發(fā)WinForm清空DataGridView控件綁定的數(shù)據(jù)
使用DataGridView控件綁定數(shù)據(jù)后有時需要清空綁定的數(shù)據(jù),在清除DataGridView綁定的數(shù)據(jù)時:
1、設(shè)置DataSource為null
this.dgvDemo.DataSource = null
這樣雖然可以清空DataGridView綁定的數(shù)據(jù),但是DataGridView的列也會被刪掉。
2、用DataGridView.Row.Clear()
this.dgvDemo.Rows.Clear()
使用這種方法會報(bào)錯,提示“不能清除此列表”,報(bào)錯信息如下:
以上兩種方法都不是想要的結(jié)果。要想保持原有的列不被刪除,就要清除原先綁定的DataTable中的數(shù)據(jù),然后重新綁定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 '項(xiàng)目代碼',XIANGMUMC AS '項(xiàng)目名稱', DANJIA AS '單價(jià)',SHULIANG AS '數(shù)量' 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; // 會報(bào)錯:提示“不能清除此列表” //this.dgvDemo.Rows.Clear(); DataTable dt = this.dgvDemo.DataSource as DataTable; dt.Rows.Clear(); this.dgvDemo.DataSource = dt; } } }
示例程序下載地址:點(diǎn)此下載
到此這篇關(guān)于清空DataGridView控件綁定數(shù)據(jù)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#根據(jù)前臺傳入實(shí)體名稱實(shí)現(xiàn)動態(tài)查詢數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了C#如何根據(jù)前臺傳入實(shí)體名稱實(shí)現(xiàn)動態(tài)查詢數(shù)據(jù)的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-04-04C#中遍歷DataSet數(shù)據(jù)集對象實(shí)例
這篇文章主要介紹了C#中遍歷DataSet數(shù)據(jù)集對象實(shí)例,經(jīng)常忘記如何操作DataSet,這里記下來并分享,讓需要的朋友可以參考下2014-08-08C#實(shí)現(xiàn)對用戶輸入數(shù)據(jù)進(jìn)行校驗(yàn)的類實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)對用戶輸入數(shù)據(jù)進(jìn)行校驗(yàn)的類,實(shí)例分析了C#針對各種用戶輸入數(shù)據(jù)的常用校驗(yàn)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03C# 執(zhí)行CMD命令并接收返回結(jié)果的操作方式
這篇文章主要介紹了C# 執(zhí)行CMD命令并接收返回結(jié)果的操作方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04