向DataGridView中添加新的一行数据,可以添加到最后一行或作为第一行
我的開發環境:Microsoft Visual Studio .net 2005
這個程序是Windows Forms Application
?
新建一個Windows Forms Application項目,打開Form1,在窗體上放一個DataGridView控件和Button,在DataGridView的Columns中添加兩列,Name分別為stuName(此處不可用“Name”,因為與控件的Name會沖突)和Age。如下圖:
?
整體代碼如下:
?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Wind
{
??? public partial class Form1 : Form
??? {
??????? int c = 0;
??????? public Form1()
??????? {
??????????? InitializeComponent();
??????? }
??????? private void button1_Click(object sender, EventArgs e)
??????? {
??????????? DataGridViewRow dr = new DataGridViewRow();
??????????? dr.CreateCells(dgv);
??????????? dr.Cells[0].Value = "h1";
??????????? dr.Cells[1].Value = (++c);
??????????? dgv.Rows.Insert(0, dr); //插入的數據作為第一行顯示
//dgv.Rows.Add(dr);??????????????????? //插入的數據作為最后一行顯示
??????? }
??? }
}
?
?
按F5運行,即可看到運行結果。下面是作為第一行插入時的運行結果:
?
總結
以上是生活随笔為你收集整理的向DataGridView中添加新的一行数据,可以添加到最后一行或作为第一行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 随机森林模型及案例(Python)
- 下一篇: Linux文件和目录权限:chmod、更