我有一个问题,我不知道问题所在。当我输入详细信息并点击我的REGISTER页面上的提交按钮时,我的视觉工作室会抛出异常。我不知道问题出在我的SQL查询中还是我的代码。所以我发布了两个
这是我的Sql查询:
Create proc spRegisteredUsers
@Name nvarchar(100),
@UserName nvarchar(100),
@Password nvarchar(200),
@ContactNo int,
@Email nvarchar(200)
as
Begin
Declare @Count int
Declare @ReturnCode int
Select @Count = COUNT(UserName)
from tblRegisteredUsers where UserName=@UserName
if @Count>0
Begin
Set @ReturnCode= -1
End
Else
Begin
Set @ReturnCode= 1
Insert into tblRegisteredUsers values(@Name,@UserName,@Password,@ContactNo,@Email)
End
Select @ReturnCode as ReturnValue
End
虽然我在下面的行中得到例外:
protected void btnRegSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string CS = ConfigurationManager.ConnectionStrings["AK"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spRegisteredUsers", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter Name = new SqlParameter("@Name", txtRegName.Text);
SqlParameter UserName = new SqlParameter("@UserName", txtRegUsername.Text);
SqlParameter Password = new SqlParameter("@Password", txtRegPassword.Text);
SqlParameter ContactNo = new SqlParameter("@ContactNo", txtRegContact.Text);
SqlParameter Email = new SqlParameter("@Email", txtRegEmail.Text);
cmd.Parameters.Add(Name);
cmd.Parameters.Add(UserName);
cmd.Parameters.Add(Password);
cmd.Parameters.Add(ContactNo);
cmd.Parameters.Add(Email);
con.Open();
int ReturnCode = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (ReturnCode == -1)
{
lblMessage.Text = "UserName already exists.";
}
else
{
Response.Redirect("~/Login.aspx");
}
}
}
}
我看到一个有趣的事情。当我从表,存储过程和cs代码中删除Name和ContactNo字段时.IT WORKS。
答案 0 :(得分:2)
试试这个:
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spRegisteredUsers", con);
cmd.CommandType = CommandType.StoredProcedure;
//use long instead...
long Contact = Convert.ToInt64(txtRegContact.Text); //convert to long here
SqlParameter Name = new SqlParameter("@Name", txtRegName.Text);
SqlParameter UserName = new SqlParameter("@UserName", txtRegUsername.Text);
SqlParameter Password = new SqlParameter("@Password", txtRegPassword.Text);
SqlParameter ContactNo = new SqlParameter("@ContactNo", Contact);
SqlParameter Email = new SqlParameter("@Email", txtRegEmail.Text);
......
您正在传递一个字符串,SQL Procedure需要int为ContactNo。
答案 1 :(得分:0)
你可能会在第一行收到错误。试试这个:
int ReturnCode = Convert.ToInt32(cmd.ExecuteScalar().ToString());