日期:2014-05-18  浏览次数:20740 次

急呀!新手:关于写不进数据库的问题
最近在学c#web应用程序入门经典,发现数据怎么也写不进数据库,调试结果也没有出错。只是出现了一个异常,但是不知道怎么调。我用的是sql2000和vs2005.希望得到高手相助,谢谢!!!
代码如下:
 protected void btnAccept_Click(object sender, EventArgs e)
  {
  if (Page.IsValid)
  {
  //save new user to the database
  SqlConnection con;
  string sql;
  SqlCommand cmd;
  StringBuilder sb = new StringBuilder();
  ArrayList values = new ArrayList();

  sb.Append("INSERT INTO[LYNN]");
  sb.Append("(UserID,Login,Password,FirstName,LastName,");
  sb.Append("PhoneNumber,Email,IsAdminstrator,Address,");
  sb.Append("CellNumber,DateOfBirth)");
  sb.Append("VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',");
  //optional values without quotes as they can be the Null value.
  sb.Append("{8},{9},{10})");

  //add required values to replace
  values.Add(Guid.NewGuid().ToString());
  values.Add(txtLogin.Text);
  values.Add(txtPwd.Text);
  values.Add(txtFName.Text);
  values.Add(txtLName.Text);
  values.Add(txtPhone.Text);
  values.Add(txtEmail.Text);
  values.Add(0);

  //add the optional values or Null
  if (txtAddress.Text != string.Empty)
  values.Add("" + txtAddress.Text + "");
  else
  values.Add("Null");

  if (txtMobile.Text != string.Empty)
  values.Add("" + txtMobile.Text + "");
  else
  values.Add("Null");

  if (txtBirth.Text != string.Empty)
  values.Add("" + txtBirth.Text + "");
  else
  values.Add("Null");

  //format the string with the array of values
  sql = string.Format(sb.ToString(), values.ToArray());

  //connect and execute the query
  con = new SqlConnection("server=localhost;database=FriendsDatabase;user id=sa;pwd=sa123456");
  cmd = new SqlCommand(sql, con);
  con.Open();

  bool doredirect = true;

  try
  {
  cmd.ExecuteNonQuery();

  }
  catch
  {
  doredirect = false;
  this.lblMessage.Visible = true;
  this.lblMessage.Text = "Insert couldn't be performed.User name may be already taken.";
  }
  finally
  {
  con.Close();//关闭连接
  }

  if (doredirect)

  Response.Redirect("Login.aspx");
  }

  else
  {
  lblMessage.Text = "Fix the following errors and retry:";
  //lblMessag