用户代码未处理SQL异常

时间:2019-05-29 00:47:40

标签: c# sql

我的代码:

    if (Page.IsValid)
    {
        DataSet.UsersDataTable oUserDataTable =
            new DataSet.UsersDataTable();

        DataSetTableAdapters.UsersTableAdapter oUserTableAdapter =
            new DataSetTableAdapters.UsersTableAdapter();

        oUserTableAdapter.FillUserByUserName(oUserDataTable, txtUserName.Text);

        if (oUserDataTable.Count!=1)
        {
            string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
            DisplayErrorMessage(strErrorMessage);
            return;
        }

        DataSet.UsersRow oUserRow = oUserDataTable[0];

        if (string.Compare(oUserRow.Password.Trim(),txtPassword.Text.Trim(),false)!=0)
        {
             string strErrorMessage =
                "UserName Or Password Is Not Correct ! Please Try Again . . . ";
             DisplayErrorMessage(strErrorMessage);
            return;
        }

        if (oUserRow.IsUserActive==false)
        {
            string strInformationMessage =
                string.Format("Dear {0} You Should Not Login At This Time , Please Contact Support",txtUserName.Text);
            DisplayInformationMessage(strInformationMessage);
            return;
        }

我得到一个错误:

  

其他信息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)

1 个答案:

答案 0 :(得分:0)

首先检查db连接是否可以打开,如果可以,那么就行了,否则抛出异常并检查连接字符串是否正确。以下代码可以帮助您进行数据库连接检查

try
{
   using (SqlConnection conn = new SqlConnection("connection"))
   {
      conn.Open();
    }
}
catch(Exception ex)
{
   MessageBox.Show(ex.Message, "Invalid Connection String");
}

在此行DataSet.UsersDataTable oUserDataTable = new DataSet.UsersDataTable();之前添加此代码