OleDbConnection conn;
DataSet ds;
OleDbDataAdapter sda;
private void Form1_Load(object sender, EventArgs e)
{
// provider=Microsoft.Jet.OleDb.4.0;Data Source=5.mdb
try
{ //连接数据库
conn = new OleDbConnection("provider=Microsoft.Jet.OleDb.4.0;Data Source=info.mdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand("select *from info", conn);
sda = new OleDbDataAdapter();//实例化适配器DataAdapter对象
sda.SelectCommand = cmd;
//设置DataAdapter对象的SelectCommand属性
ds = new DataSet();
//实例化DataSet
sda.Fill(ds, "info");
dataGridView1.DataSource = ds.Tables[0];
}
catch
{
MessageBox.Show("连接数据库失败!");
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
txtNo.Text = dataGridView1.SelectedCells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedCells[1].Value.ToString();
txtsex.Text = dataGridView1.SelectedCells[2].Value.ToString();
txtage.Text = dataGridView1.SelectedCells[3].Value.ToString();
}
//更新
private void button1_Click(object sender, EventArgs e)
{
DataTable dt=ds.Tables["info"];
sda.FillSchema(dt,SchemaType.Mapped);
DataRow dr = dt.Rows.Find(txtNo.Text);
dr["姓名"]=txtName.Text.Trim();
dr["性别"]=txtsex.Text.Trim();
dr["年龄"]=txtage.Text.Trim();
OleDbCommandBuilder cmdbuder = new OleDbCommandBuilder(sda);
sda.Update(dt);
}
//添加
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand cmd1 = new OleDbCommand("insert into info values('"+txtNo.Text.Trim()+"','"+txtName.Text.Trim()+"','"+txtsex.Text.Trim()+"','"+txtage.Text.Trim()+"')",conn);
cmd1.ExecuteNonQuery();
}