菜鸟求大神,一个简单的注册网站,总是出现无法将int类型转换成string的错误,数据库Age字段是Int
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string userid = this.lbUserID.Text.Trim();
string password = this.lbPassword.Value.Trim();
string password1 = this.lbpassword1.Value.Trim();
string xb = this.tbXB.Text.Trim();
int age = int.Parse(this.tbAge.Text.ToString());
string tel = this.tbTel.Text.Trim();
string email = this.tbEmail.Text.Trim();
if (password == password1)
{
AddUser(userid, password,xb,age,tel,email);
Response.Redirect("Viewer.aspx");
}
}
private void AddUser(string userid, string password,string xb,int age,string tel,string email)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Usermanagement.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "insert into [UserInfo](UserID,Password,XB,Age,Tel,[E-mail])values(@un,@pw,@xb,@age,@tel,@email)";
cmd.Parameters.AddWithValue("un", userid); // 将username 赋值给命令行的"un”
cmd.Parameters.AddWithValue("pw", password); // 将Password 赋值给命令行的"pw”,以下类似
cmd.Parameters.AddWithValue("xb", xb);
cmd.Parameters.AddWithValue("age", age);
cmd.Parameters.AddWithValue("tel", tel);
cmd.Parameters.AddWithValue("email",email);
cmd.ExecuteNonQuery(); // 执行数据库命令
lbUserID.Text = ""; // 清空用户输入框
lbPassword.Value = ""; // 清空密码输入框
cmd.Dispose(); // 丢弃命令
con.Dispose(); // 丢弃连接
this.Session["Username"] = userid;
}
}
[解决办法]
这种情况一般是你传递到数据库内的值与你建数据库表里的字段类型不一样,
建议楼主可以看下数据库表的字段类型,然后跟踪看下你cmd.Parameters.AddWithValue
的值,是否与数据库字段类型一致。
[解决办法]
cmd.Parameters.AddWithValue("un", userid); // 将username 赋值给命令行的"un”
cmd.Parameters.AddWithValue("pw", password); // 将Password 赋值给命令行的"pw”,以下类似
cmd.Parameters.AddWithValue("xb", xb);
cmd.Parameters.AddWithValue("age", age);
cmd.Parameters.AddWithValue("tel", tel);
cmd.Parameters.AddWithValue("email",email);