Buzz
Buzz

Reputation: 55

Validating user input from textbox c#

I am trying to validate a user input to a given string. I am able to do this in java with this code

        String username = request.getParameter("txtUsername");
        String password = request.getParameter("txtPassword"];)

   if (username.equals("john") && (password.equals("smith"))){

        out.println("Success");

    }
    else{

         out.println("validation failed");
     }

but it returns a NullReferenceException in C# using this same code.

       {

    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        String username = Request.QueryString["txtUsername"] ?? "";
        String password = Request.QueryString["txtPassword"] ?? "";

        try {
        if(username.Equals("john") && (password.Equals("smith"))){

            lblLogin.Text = "Success";
            Response.Redirect("ModelProfile.aspx");
        }
        else

        {
            lblLogin.Text = "Failed";
             Response.Redirect("Login.aspx");
        }

        }
        catch
        {
            lblLogin.Text = "Please type in some valid credentials";

        }

    }

Here is the text boxes in the aspx page looks like:

            <div id="loginUsername">
                <asp:Label ID="lblUsername" runat="server" Text="Username:"></asp:Label>

                <asp:TextBox ID="txtUsername" runat="server"   CssClass="mytext"></asp:TextBox>
            </div>

        <div id="loginPassword">
            <asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server" CssClass="mytext"></asp:TextBox>

        </div>
        <div id="loginButton">

            <asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" OnClick="btnLogin_Click" />
            <asp:Label ID="lblLogin" runat="server" Text=""></asp:Label>

        </div>
    </div>

Please any ideas on how I can solve this will be appreciated. Thanks

Upvotes: 0

Views: 384

Answers (1)

Steve
Steve

Reputation: 216273

You could easily fix your problem with

    String username = Request.QueryString["txtUsername"] ?? "";
    String password = Request.QueryString["txtPassword"] ?? "";

The ?? is the C# Null Coalescing operator

However looking at your code, it seems that you don't have to work with the QueryString because the button login is on the same page of your textboxes. If this is correct then you should reference the textbox directly. No need to check for null because the textbox text property is never null (if you really want to be very precise you could add a Trim)

    String username = txtUsername.Text.Trim();
    String password = txtPassword.Text.Trim();

Upvotes: 2

Related Questions