本文小編為大家詳細介紹“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控件綁定的數據”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。