c#中dataGridView的一些操作
By
admin
at 2023-01-29 • 0人收藏 • 779人看过
DataTable db;
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.MultiSelect = false;
db= new DataTable();
db.Columns.Add("id", System.Type.GetType("System.Int32"));//第一种方式指定
db.Columns.Add("name",typeof(string));//第二种方式指定
db.Columns.Add("year");
for (int i = 0; i < 100; i++)
{
var row = db.NewRow();
//添加数据
row.ItemArray = new object []{i,i,i};
db.Rows.Add(row);
}
dataGridView1.DataSource = db;
}
private void button1_Click(object sender, EventArgs e)
{
var row = db.NewRow();
row.ItemArray = new object[] {db.Rows.Count, "hello", "57" };
//db.Rows.Add(row);
db.Rows.InsertAt(row, 0);
//为了把表前面的三角符号也跟随选中项,需要指定到哪一个确定的单元格才行
//第一种方式
//dataGridView1.Rows[0].Cells[0].Selected = true;
//滚动到指定项
//dataGridView1.FirstDisplayedScrollingRowIndex= 0;
//第二种方式
dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
}
1 个回复 | 最后更新于 2023-02-05
登录后方可回帖
using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace DataGridViewWithSQL { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // 创建一个SqlConnection对象 SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=TestDB;Integrated Security=True"); // 创建一个SqlCommand对象 SqlCommand cmd = new SqlCommand("SELECT * FROM Users", con); // 创建一个SqlDataAdapter对象 SqlDataAdapter adapter = new SqlDataAdapter(cmd); // 创建一个DataTable对象 DataTable dt = new DataTable(); // 使用DataAdapter的Fill方法从数据库中读取数据 adapter.Fill(dt); // 将DataTable绑定到DataGridView控件 dataGridView1.DataSource = dt; } } }DataGridView与SQL Server数据库交互