溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#開發WinForm中怎么清空DataGridView控件綁定的數據

發布時間:2022-03-08 09:06:29 來源:億速云 閱讀:1276 作者:iii 欄目:開發技術

本文小編為大家詳細介紹“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()

使用這種方法會報錯,提示“不能清除此列表”,報錯信息如下:

C#開發WinForm中怎么清空DataGridView控件綁定的數據

以上兩種方法都不是想要的結果。要想保持原有的列不被刪除,就要清除原先綁定的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控件綁定的數據”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女