using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataBind(); //调用数据绑定,初始化数据
}
protected void DataBind()
{
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataBind(); //调用数据绑定,初始化数据
}
protected void DataBind()
{
SqlConnection con = new SqlConnection("server=.;database=goodluck;uid=sa;pwd=;");
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from persons where age>3 order by age asc", con);
sda.SelectCommand = cmd;
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from persons where age>3 order by age asc", con);
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0]; //把第一个表设置为数据源
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0]; //把第一个表设置为数据源
//与ASP.NET里GridView控件不同的是这里的DataGridView不需要DataBind()
}
}
}
}
}
}
DataGridView里绑定了DataSet的数据,我们要想删除DataGridView里的某一行数据,怎么办?
假设DataGridView的第一列是id(int型)
int id =Convert.ToInt32(this.dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value); //获取行ID号
然后组织SQL语句就OK了。
int id =Convert.ToInt32(this.dataGridView1[0, dataGridView1.CurrentCell.RowIndex].Value); //获取行ID号
然后组织SQL语句就OK了。
用datagridview更新数据库 (2008-04-30 12:59:38) 标签:datagridview 数据库 更新 it
基于单表datagridview可以用此方法更新,基于多表datagridview还是用sqlcommand的更新方法更新吧!呵呵!
private SqlDataAdapter adapter = new SqlDataAdapter(); //建立数据适配器
private DataTable customers = new DataTable(); //建立数据表
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection ("server=192.168.1.122;uid=sa;pwd=sa;database=goods");
connection.Open();
SqlCommand mycomm = new SqlCommand("select * from DepartMent", connection);
adapter.SelectCommand = mycomm;
adapter.Fill(customers);
this.dataGridView1.DataSource = customers; //设置数据源
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection ("server=192.168.1.122;uid=sa;pwd=sa;database=goods");
connection.Open();
SqlCommand mycomm = new SqlCommand("select * from DepartMent", connection);
adapter.SelectCommand = mycomm;
adapter.Fill(customers);
this.dataGridView1.DataSource = customers; //设置数据源
}
private void button1_Click(object sender, EventArgs e)
{
SqlCommandBuilder mybuikder = new SqlCommandBuilder(adapter);
adapter.Update(customers);
SqlCommandBuilder mybuikder = new SqlCommandBuilder(adapter);
adapter.Update(customers);
}
注意键列信息,所更改的数据表必须有主键!否则无法更新.
更改列名为中文应该使用:
dataGridView1.Columns[0].HeaderText = "序号";
本文转自 qianshao 51CTO博客,原文链接:http://blog.51cto.com/qianshao/201798,如需转载请自行联系原作者