我有一个登录表单并修改了其他来源的一些代码以使其适合我的情况。由于数字为空或“无限”,登录无效时出现错误。
public int Validate_Login(String Username, String Password)
{
//SqlConnection con = new SqlConnection(@"User id=judgment_day;Password=Kit$hen;Server=216.40.232.82, 2153;Database=new_judgment-system");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CityCollectionCSharp.Properties.Settings.newCityCollectionConnectionString"].ConnectionString);
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandType = CommandType.StoredProcedure;
cmdselect.CommandText = "[dbo].[prcLoginv]";
cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username;
cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value = Password;
cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4);
cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;
cmdselect.Connection = con;
int Results = 0;
try
{
con.Open();
cmdselect.ExecuteNonQuery();
Results = (int)cmdselect.Parameters["@OutRes"].Value;
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
return Results;
}
错误发生在这一行:
Results = (int)cmdselect.Parameters["@OutRes"].Value;
我将如何进行错误处理,所以当它不是一个有效的整数时,它将触发代码所在的无效登录:
protected void btnlogin_Click(object sender, EventArgs e)
{
int Results = 0;
if (txtUsername.Text != null && txtPassword.Text != null)
{
Results = Validate_Login(txtUsername.Text, txtPassword.Text);
if (Results > 0)
{
lblMessage.Text = "Login is Good";
GlobalVariables.Globals.SetGlobalInt(Results);
lblMessage.Text = "'" + GlobalVariables.Globals.GlobalInt + "'";
this.Hide();
frmSwitch frm = new frmSwitch();
frm.Show();
}
else
{
lblMessage.Text = "Invalid Login";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
else
{
lblMessage.Text = "Please make sure that the username and the password is Correct";
}
}