无法使用TableAdapters

时间:2015-07-11 14:54:25

标签: c# mysql asp.net tableadapter

每次在TextBox中输入字符时,我都会尝试检查表格中是否存在用户名。这是我的代码:

register.aspx.cs文件中,TextChanged上有TextBox个事件:

protected void username_txt_TextChanged(object sender, EventArgs e)
{
    string check = authentication.checkUsername(username_txt.Text);

    if(check == "false")
    {
        username_lbl.Text = "Available";
    }
    else
    {
        username_lbl.Text = "Not Available";
    }
}

它称之为:

public static string checkUsername(string Username)
{
    userInfoTableAdapters.usersTableAdapter userInfoTableAdapters = new userInfoTableAdapters.usersTableAdapter();
    DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);
    DataRow row = userDataTable.Rows[0];
    int rowValue = System.Convert.ToInt16(row["Users"]);

    if (rowValue == 0)
    {
        return "false";
    }
    else
    {
        return "true";
    }
}

正在执行的查询是:

SELECT COUNT(username) AS Users FROM users WHERE (username = @Username)

出于某种原因,它在这一行上不断突破:

DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);

它出现错误:

  

无法启用约束。一行或多行包含违反非null,唯一或外键约束的值。

只是因为,我的表中的用户名字段是唯一且不是空的,我尝试过只执行查询本身,它完美地工作,因此它不在查询结束。

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的查询不会返回该行 - 因此在这种情况下使用返回TableAdapter的{​​{1}}查询是不合适的。

我建议您使用以下函数之类的查询。我冒昧地实际返回了布尔....

DataTable

TableAdapter支持对表对象进行标量查询,当您添加并命名查询时,请检查该查询的属性并确保其public static bool checkUsername(string userName) { SqlClient.SqlCommand withCmd = new SqlClient.SqlCommand(); bool result = false; withCmd.Connection.Open(); withCmd.CommandType = CommandType.text; withCmd.CommandText = "SELECT COUNT(username) AS Users FROM users WHERE (username = @Username)" withCmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Username", System.Data.SqlDbType.VarChar, 16)).Value = userName; try { int intResult; object scalarResult = withCmd.ExecuteScalar(); if ((scalarResult != DBNull.Value) && (scalarResult != null) && (int.TryParse(scalarResult, out intResult))) result = (intResult==1); } catch (Exception ex) { result = false; // hmm, bad...can't tell handle error... } finally { // only close if we opened the connection above ... withCmd.Connection.Close(); } } return result; } 是标量。然后它将返回整数值,而不是行!

TableAdapter with Scalar Query showing properties

另一方面,如果要保留结构,请更改查询以实际返回ExecuteMode,例如

row

并使checkUsername()函数的结果取决于返回的行数(应为1或0 ....)