DataGridView:DataGridView控件清空綁定的數據

使用DataGridView控件綁定數據後有時須要清空綁定的數據,在清除DataGridView綁定的數據時:this

一、設置DataSource爲nullspa

this.dgvDemo.DataSource = null

這樣雖然能夠清空DataGridView綁定的數據,可是DataGridView的列也會被刪掉。orm

二、用DataGridView.Row.Clear()blog

this.dgvDemo.Rows.Clear()

使用這種方法會報錯,提示「不能清除此列表」,報錯信息以下:cmd

以上兩種方法都不是想要的結果。要想保持原有的列不被刪除,就要清除原先綁定的DataTable中的數據,而後從新綁定DataTablestring

DataTable dt = this.dgvDemo.DataSource as DataTable;
dt.Rows.Clear();
this.dgvDemo.DataSource = dt;

示例代碼以下:it

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;
        }
    }
}

示例程序下載地址:https://pan.baidu.com/s/1brhiWKBio

相關文章
相關標籤/搜索