仅当数据库中没有指定用户时,才会发生此错误。我不知道为什么会这样。我以为我处理了例外,但显然没有。
在我对代码和存储过程进行更改之前,dbnull处理都很好,错误再次出现。
我已经尝试过,但是效果不佳。
if (!DBNull.Value.Equals(cmd.ExecuteScalar()))
{
userId = Convert.ToInt32(cmd.ExecuteScalar());
}
错误类型
Object cannot be cast from DBNull to other types.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Object cannot be cast from DBNull to other types.
Source Error:
Line 31: try
Line 32: {
Line 33: userid = Convert.ToInt32(cmd.ExecuteScalar());
Line 34: }
Line 35: catch (SqlException sqlEx)
[InvalidCastException: Object cannot be cast from DBNull to other types.]
System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) +52
System.Convert.ToInt32(Object value) +30
clockin.RegisterUser(Object sender, EventArgs e) in C:\Users\na3307\source\repos\WebApplication2\WebApplication2\clockin.aspx.cs:33
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9782698
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +204
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639
aspx
protected void RegisterUser(object sender, EventArgs e)
{
int userid = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("clocking"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
Session["username"] = txtUsername.Text;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@b", DropDownList1.SelectedValue.ToString());
cmd.Connection = con;
con.Open();
try
{
userid = Convert.ToInt32(cmd.ExecuteScalar());
}
catch (SqlException sqlEx)
{
if (sqlEx.Message.StartsWith("dbnull name "))
{
Label1.Text = "DBnull";
}
else
throw;
}
string message = string.Empty;
switch (userid)
{
case -1:
message = "You have already clocked in, TRY AGAIN LATER";
Label1.Text = message;
break;
case -2:
message = "Not ready to clock in yet OR User not registered!";
Label1.Text = message;
break;
default:
message = txtUsername.Text + ", You have clocked in successfully.";
Label1.Text = message;
break;
}
}
}
}
存储过程
CREATE PROCEDURE [dbo].[clocking]
@Username NVARCHAR(100),
@b nvarchar(100)
AS
BEGIN
SET NOCOUNT ON;
SELECT SCOPE_IDENTITY() -- UserId
IF EXISTS(select createddate,count(*) from clockin where username = @Username and eventname = @b
group by createddate
HAVING COUNT(createddate) = 1
)
BEGIN
SELECT -1 -- Username exists.
END
ELSE IF EXISTS(SELECT userid FROM selected WHERE Username = @Username and datepart(hour, CURRENT_TIMESTAMP) BETWEEN (select timein from timing) and (select timeout from timing) and
eventname = @b)
BEGIN
INSERT INTO [clockin]
([Username]
,[CreatedDate],
[time],
[eventname]
)
VALUES
(@Username
,GETDATE(),
CURRENT_TIMESTAMP,
@b
)
END
ELSE IF NOT EXISTS(SELECT userid FROM selected WHERE Username = @Username and eventname = @b)
BEGIN
SELECT -2 -- Not ready to clock in yet OR User not registered!
END
BEGIN
update selected
set times =
(select count (*) from clockin
where selected.username = clockin.username)
END
END