WinForm中利用DataSet向DataGridView中添加多行數據


怎樣利用DataSet向DataGridView中添加數據呢?很簡單:編寫添加按鈕的單擊事件方法
示例代碼:
private void btnAdd_Click(object Sender,EventArgs e)
{
    //創建DataSet對象
    DataSet ds = new DataSet();
    //創建DataTable對象
    DataTable dt = new DataTable();
    //創建列
    dt.Columns.Add("姓名",typeof(string));
    dt.Columns.Add("年齡",typeof(int));
    //創建行
    DataRow row = dt.NewRow();
    //添加數據
    row[0] = this.txtName.Text.Trim();
    row[1] = this.txtAge.Text.Trim();
    //將行添加到數據表的行集合中
    dt.Rows.Add(row);
    //將數據表添加到DataSet中
    ds.Tables.Add(dt);
    //將DataSet中的表添加到DataGridView之中
    this.dataGridView1.DataSource = ds.Tables[0];
}

但是這樣,只能一次添加一條數據,而且在DataGridView中顯示的始終是一條數據,不能實現數據累加,
那該怎么辦呢?
其實很簡單,只需將上面的代碼稍稍改動一下位置,不用添加也不用減少代碼。

首先,在窗體類中創建兩個全局對象,即DataSet和DataTable對象
示例代碼:
    //創建DataSet對象
    DataSet ds = new DataSet();
    //創建DataTable對象
    DataTable dt = new DataTable();
其次,在窗體加載事件之中創建數據表的列,同時將數據表添加到DataSet之中
示例代碼:
    private void Form1_Load(object sender, EventArgs e)
        {
            //創建數據列
            dt.Columns.Add("姓名",typeof(string));
            dt.Columns.Add("年齡",typeof(int));
            ds.Tables.Add(dt);
        }
再次,添加按鈕的單擊事件只負責添加數據行並向行中添加數據,將行添加到行集合中,同時顯示在      DataGridView之中
示例代碼:
private void button1_Click(object sender, EventArgs e)
        {
            //添加行
            DataRow row = dt.NewRow();
            //添加數據
            row[0] = this.txtName.Text.Trim();
            row[1] = this.txtAge.Text.Trim();
            //將行添加到數據表的行集合中
            dt.Rows.Add(row);
            //將DataSet中的表添加到DataGridView之中
            this.dataGridView1.DataSource = ds.Tables[0];

        }

到此,即可實現利用DataSet向DataGridView中添加多行數據的效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM