添加用户

作者在 2007-04-30 19:08:00 发布以下内容

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace AddUser
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.GroupBox groupBox1;
  private System.Windows.Forms.TextBox UserName;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.TextBox Password;
  private System.Windows.Forms.Button buttonAdd;
  private System.Windows.Forms.Button buttonCancel;
  private System.Windows.Forms.Label label3;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  private DataSet myDataSet=null;

  public DataSet MyDataSet
  {
   get
   {
    return myDataSet;
   }
   set
   {
    myDataSet = ;
   }
  }

  private DataSet LoadDataSet()
  {
   //创建与数据库连接
   SqlConnection con = new SqlConnection("server = .;uid = sa;pwd = sa;database = ex;");
   con.Open();
   //创建连接字符串
   SqlDataAdapter da = new SqlDataAdapter("select * from UserInfo",con);
   DataSet ds = new DataSet();
   da.Fill(ds,"UserInof");
   //
   SqlCommandBuilder thisBuilder = new SqlCommandBuilder(da);
   DataRow Row = ds.Tables[0].NewRow();
   Row[0] = this.UserName.Text.Trim();
   Row[1] = this.Password.Text.Trim();
   //创建主键
   DataColumn[] key = new DataColumn[1];
   key[0] = ds.Tables[0].Columns[0];
   ds.Tables[0].PrimaryKey = key;
   //查找
   DataRow findRow = ds.Tables[0].Rows.Find(this.UserName.Text.Trim());
   //判断添加前查找是否成功
   if(findRow == null)
   {
    ds.Tables[0].Rows.Add(Row);
    //更新数据库
    da.Update(ds,ds.Tables[0].ToString());
    //判断添加后查找是否成功
    if((findRow = ds.Tables[0].Rows.Find(this.UserName.Text.Trim())) != null)
    {
     MessageBox.Show("添加成功","提示");
     this.UserName.Text = "";
     this.Password.Text = "";
     this.UserName.Focus();
    }
    else
    {
     MessageBox.Show("添加失败,请重试!","警告");
    }
   }
   else
   {
    MessageBox.Show("该用户已存在","提示");
    this.UserName.Text = "";
    this.Password.Text = "";
    this.UserName.Focus();
   }
           
   return ds;
  }

  private void Init()
  {
   MyDataSet = LoadDataSet();
  }

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   

C# | 阅读 827 次
文章评论,共0条
游客请输入验证码
最新评论