C#system.nullreferenceException不在用户代码中处理

时间:2016-03-26 15:19:04

标签: asp.net c#-3.0

我正在尝试创建从C#到SQL Server的连接,并发生NullReferenceException

我已经尝试了几次,但没有找到治愈我的问题。它说错误发生在line 3。我认为这可能是SQL Server和C#代码之间的连接问题。

以下是C#的代码:

protected void Button1_Click(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Insert_User"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", TextBoxUN.Text.Trim());
                cmd.Parameters.AddWithValue("@Email", TextBoxEmail.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", TextBoxPswd.Text.Trim());
                cmd.Connection = con;
                con.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
        }
        string message = string.Empty;
        switch (userId)
        {
            case -1:
                message = "Username already exists.\\nPlease choose a different username.";
                break;
            case -2:
                message = "Supplied email address has already been used.";
                break;
            default:
                message = "Registration successful.\\nUser Id: " + userId.ToString();
                break;
        }
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }

登录表单的HTML代码如下:

<table class="auto-style1">
        <tr>
            <td class="auto-style2">Username</td>
            <td class="auto-style3">

                <asp:TextBox ID="TextBoxUN" runat="server" OnTextChanged="TextBoxUN_TextChanged" Width="180px"></asp:TextBox>

            </td>
            <td>
                <asp:RequiredFieldValidator ID="Label1" runat="server" ControlToValidate="TextBoxUN" ErrorMessage="Username is required" ForeColor="Red"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="auto-style4">&nbsp;</td>
            <td class="auto-style5">&nbsp;</td>
            <td class="auto-style6">&nbsp;</td>
        </tr>
        <tr>
            <td class="auto-style2">E-mail</td>
            <td class="auto-style3">
                <asp:TextBox ID="TextBoxEmail" runat="server" Width="180px"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="E-mail is required" ForeColor="Red"></asp:RequiredFieldValidator>
                <br />
                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBoxEmail" ErrorMessage="E-mail entered is not correct" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td class="auto-style2">Password</td>
            <td class="auto-style3">
                <asp:TextBox ID="TextBoxPswd" runat="server" TextMode="Password" Width="180px"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBoxPswd" ErrorMessage="Password is required" ForeColor="Red"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="auto-style2">Confirm-Password</td>
            <td class="auto-style3">
                <asp:TextBox ID="TextBoxRPswd" runat="server" TextMode="Password" Width="180px"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="TextBoxRPswd" ErrorMessage="Confirm your password" ForeColor="Red"></asp:RequiredFieldValidator>
                <br />
                <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBoxPswd" ControlToValidate="TextBoxRPswd" ErrorMessage="Enter Correct Password" ForeColor="Red"></asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td class="auto-style7"></td>
            <td class="auto-style8"></td>
            <td class="auto-style9"></td>
        </tr>
        <tr>
            <td class="auto-style2">&nbsp;</td>
            <td class="auto-style3">&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
    </table>
    <asp:Button ID="Button1" runat="server" BorderStyle="Ridge" OnClick="Button1_Click" Text="Register" />
    <input id="Reset1" type="reset" value="reset" />

1 个答案:

答案 0 :(得分:0)

我猜错误是因为SqlDataAdapter,因为你没有指定任何东西。此外,您不需要SqlDataAdapter作为一个值。将您的代码更改为:

int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("Insert_User", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Username", TextBoxUN.Text.Trim());
        cmd.Parameters.AddWithValue("@Email", TextBoxEmail.Text.Trim());
        cmd.Parameters.AddWithValue("@Password", TextBoxPswd.Text.Trim());
        try
        {
            con.Open();
            userId = Convert.ToInt32(cmd.ExecuteScalar().ToString());
        }
        catch(Exception ex)
        {
            Response.Write("<script language='javascript'>alert('" + ex.Message.ToString() + "');</script>");//It will throw an alert with an exception
        }
        finally
        {
            con.Close();
        }
    }
    string message = string.Empty;
    switch (userId)
    {
        case -1:
            message = "Username already exists.\\nPlease choose a different username.";
            break;
        case -2:
            message = "Supplied email address has already been used.";
            break;
        default:
            message = "Registration successful.\\nUser Id: " + userId.ToString();
            break;
    }
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
}

希望有所帮助