C#開發(fā)WinForm清空DataGridView控件綁定的數(shù)據(jù)
使用DataGridView控件綁定數(shù)據(jù)后有時(shí)需要清空綁定的數(shù)據(jù),在清除DataGridView綁定的數(shù)據(jù)時(shí):
1、設(shè)置DataSource為null
this.dgvDemo.DataSource = null
這樣雖然可以清空DataGridView綁定的數(shù)據(jù),但是DataGridView的列也會(huì)被刪掉。
2、用DataGridView.Row.Clear()
this.dgvDemo.Rows.Clear()
使用這種方法會(huì)報(bào)錯(cuò),提示“不能清除此列表”,報(bào)錯(cuò)信息如下:

以上兩種方法都不是想要的結(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會(huì)將DataGridView的列也刪掉
//this.dgvDemo.DataSource = null;
// 會(huì)報(bào)錯(cuò):提示“不能清除此列表”
//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# Winform調(diào)用百度接口實(shí)現(xiàn)人臉識(shí)別教程(附源碼)
這篇文章主要介紹了C# Winform調(diào)用百度接口實(shí)現(xiàn)人臉識(shí)別教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
C#?線程切換后上下文都去了哪里(.NET高級調(diào)試分析)
總會(huì)有一些朋友問一個(gè)問題,在 Windows 中線程做了上下文切換,請問被切的線程他的寄存器上下文都去了哪里?這個(gè)問題其實(shí)比較底層,如果對操作系統(tǒng)沒有個(gè)體系層面的理解以及做過源碼分析,其實(shí)很難說明白,這篇我們就從.NET高級調(diào)試的角度分析,需要的朋友可以參考下2023-12-12
C#實(shí)現(xiàn)OFD格式與PDF格式的互轉(zhuǎn)
OFD格式的文檔是一種我國獨(dú)有的國家標(biāo)準(zhǔn)版式的文檔。本文將通過C#程序介紹如何實(shí)現(xiàn)由OFD與PDF的互相轉(zhuǎn)換,感興趣的小伙伴可以了解一下2022-02-02
講解C#設(shè)計(jì)模式編程中享元模式的運(yùn)用
這篇文章主要介紹了C#設(shè)計(jì)模式編程中享元模式的運(yùn)用,享元模式主張限制對象的數(shù)量來優(yōu)化內(nèi)存使用,需要的朋友可以參考下2016-02-02
C# 正則判斷一個(gè)數(shù)字的格式是否有逗號的代碼
c#正則判斷一個(gè)格式化數(shù)字里是否有逗號的解決方法2008-07-07

