在VS2010中数据源面板点击“添加数据源”,然后按照提示进行,之后定义数据库实体类。这里直接通过字符窜连接,在dataGrid中显示数据表所有的数据,将控件中的数据添加到数据库中并更新datagrid,以下是点击界面添加按钮所触发的事件,
//将空间中的字符付给新定义的变量
string userID = this.txtID.Text.Trim();
string userName = this.txtUser.Text.Trim();string Password1 = this.txtPassword1.Password.Trim();
string Password2 = this.txtPassword2.Password.Trim();
//数据库连接字符串
string sqlstr = "Data Source=DAVYLIU-PC\\HEHE;Initial Catalog=GuZhang;Persist Security Info=True;User ID=sa;Password=000000";
using (SqlConnection sqlcnn = new SqlConnection(sqlstr))
{
sqlcnn.Open();//打开链接
int flag = 0;//设置检验用户是否存在的标志
using (SqlCommand sqlcmm = sqlcnn.CreateCommand())
{
sqlcmm.CommandText = "select ID, name,password from users";
SqlDataReader reader = sqlcmm.ExecuteReader();
while (reader.Read())
{
if (userID == reader.GetString(0) || userName == reader.GetString(1))
{
System.Windows.MessageBox.Show("用户已经存在");
flag += 1;
}
}
}
sqlcnn.Close();//关闭数据库连接
if (flag == 0)
{
sqlcnn.Open();//重新打开数据库连接,若不关闭后重新打开,会出现SqlDataReader重复的错误,因为 cmd.ExecuteNonQuery();会自动生成一 个SqlDataReader的对象
int count = 0;//插入成功的标志
using (SqlCommand cmd = sqlcnn.CreateCommand())
{
cmd.CommandText = "INSERT INTO users VALUES('" + userID + "','" + userName + "','" + Password1 + "')";
cmd.ExecuteNonQuery();//执行插入命令
//重新绑定更新datagird数据
cmd.CommandText = "select ID, name,password from users";DataSet dt = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
this.dataGrid1.ItemsSource = dt.Tables[0].DefaultView;
count += 1;
}
if (count > 0)
{
System.Windows.MessageBox.Show("你已经插入成功!");
txtID.Text = "";
txtUser.Text = "";
txtPassword1.Password = "";
txtPassword2.Password = "";
}
}
}