附件:http://files.cnblogs.com/xe2011/AccessAddDataOleDbDataAdapter.rar
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Data.Common; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private OleDbConnection oleDbConnection1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=MangerDataBase.mdb"); private void Form1_Load(object sender, EventArgs e) { DataSet dataSet1 = new DataSet(); oleDbConnection1.Open(); //加载所有用户名 OleDbDataAdapter oleDbDataAdapter1 = new OleDbDataAdapter("", oleDbConnection1); oleDbDataAdapter1.SelectCommand.CommandText = "SELECT User FROM UserInfo"; oleDbDataAdapter1.Fill(dataSet1); comboBox1.DataSource = dataSet1.Tables[0].DefaultView; comboBox1.DisplayMember = "User"; comboBox1.ValueMember = "User"; //加载人员类型 DataSet dataSet2 = new DataSet(); oleDbDataAdapter1.SelectCommand.CommandText = "SELECT RoleName FROM Roles"; oleDbDataAdapter1.Fill(dataSet2); comboBox2.DataSource = dataSet2.Tables[0].DefaultView; comboBox2.DisplayMember = "RoleName"; comboBox2.ValueMember = "RoleName"; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { oleDbConnection1.Close(); } //确定 private void buttonOk_Click(object sender, EventArgs e) { if (comboBox1.Text.Trim() == "" || textBox1.Text.Trim() == "" || textBox2.Text.Trim() == "" || comboBox2.Text.Trim() == "") { MessageBox.Show("请填写完整信息!"); } else { if (textBox1.Text.Trim() != textBox2.Text.Trim()) { MessageBox.Show("两次密码输入不一致,请重新输入!"); } else { oleDbConnection1.Close(); oleDbConnection1.Open(); OleDbCommand oleDbCommand1 = new OleDbCommand("", oleDbConnection1); string sql = "SELECT user FROM UserInfo WHERE user='" + textBox1.Text.Trim() + "'"; oleDbCommand1.CommandText = sql; if (oleDbCommand1.ExecuteScalar() == null) { //user pswd type sql = "INSERT INTO UserInfo VALUES('" + comboBox1.Text.Trim() + "','" + textBox1.Text.Trim() + "','" + comboBox2.Text.Trim() + "')"; oleDbCommand1.CommandText = sql; oleDbCommand1.ExecuteNonQuery(); MessageBox.Show("用户添加成功!"); } else { MessageBox.Show("该用户已经存在,请重新输入!"); oleDbConnection1.Close(); } } } } } }