Question

I have following code and now I want to call a stored procedure of SQL, when submit button is clicked.

Can anyone help me where I should place the code that calls a SP when submit button is clicked?

Default.aspx

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Login Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">

<strong>Login Form</strong>

<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"/>
<asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please enter Username" ControlToValidate="txtUserName" runat="server" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPWD" runat="server" TextMode="Password"/>
<asp:RequiredFieldValidator ID="rfvPWD" runat="server" ControlToValidate="txtPWD" ErrorMessage="Please enter Password"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from Log_Users where UserName =@username and Password=@password", con);
        cmd.Parameters.AddWithValue("@username", txtUserName.Text);
        cmd.Parameters.AddWithValue("@password", txtPWD.Text);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            Response.Redirect("Details.aspx");
        }
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username Or Password')</script>");
        }
    }
}

Details.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Details.aspx.cs" Inherits="Details" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table align="center">
        <tr>
    <td>
      <asp:Label ID="lblDisplay" runat="server" Text="Welcome to our sample Site" Font-Bold="true"></asp:Label>
    </td>
    </tr>
    </table>

    </div>
    </form>
</body>
</html>

Details.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Details : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
Was it helpful?

Solution

Write a stored procedure with your select statement:

select * from Log_Users where UserName =@username and Password=@password

and alter your ADO.net code to consume this Stored procedure as,

 SqlCommand cmd = new SqlCommand("your sp name", con);

 cmd.CommandTpe = CommandType.StoredProcedure;

OTHER TIPS

You can use stored procedure based command text instead of using normal command text; Firstly create a storedproedure with out parameter(as well as in parameters): In Parameters are to check the username and password against the table and Out Parameter is to return whether user is a valid one or not after checking against the database.

So, make use of

cmd.CommandText="StoredProcedureName";
cmd.CommandType=CommandType.StoredProcedure;

And Use out and in parameters; And after getting the out parameter value, you can redirect to the details/error page according to the credentials provided by the user.. :)

Instead of the query that you are passing to command object in the below line-Pass the stored procedure name. It should be in the Button click event. You have written teh code at the right place.

    SqlCommand cmd = new SqlCommand("StoredProcedureName", con);

   cmd.CommandType=CommandType.StoredProcedure;

  cmd.ExecuteReader()

I hope this helps

the following is the complete solution u r looking for,

  1. the stored procedure:

    use [YOURDB]

    go

    IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'sp_Login') BEGIN DROP Procedure [dbo].[sp_Login] END

    SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON GO

    /* File Name : sp_Login.sql Description : Author : Vinay.T Date : */

    CREATE Procedure [dbo].[sp_Login] ( @Username VarChar(50) ,@UPassword varChar(50) ,@OutRes int output

    ) AS

    BEGIN SET NOCOUNT ON

    DECLARE @ErrMsg NVARCHAR(510) -- ,@ErrorSeverity INT --16 if business error BEGIN

    SET @OutRes = (SELECT count(*) FROM Log_Users WHERE Username = @Username And [Password] = @UPassword)

    END GOTO SUCCESS

    SUCCESS: RETURN 1 CRASH: RAISERROR (@ErrMsg, @ErrorSeverity, 1) WITH NOWAIT END GO GRANT EXEC ON [dbo].[sp_Login] TO PUBLIC

    GO

2:the button click event code:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("sp_Login", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Username", txtUserName.Text);
        cmd.Parameters.AddWithValue("@UPassword", txtPWD.Text);
        cmd.Parameters.Add("@OutRes", SqlDbType.Int).Direction = ParameterDirection.Output;
        cmd.ExecuteNonQuery();

        int output = (int)cmd.Parameters["@OutRes"].Value;
        if (output == 1)
        {
            Response.Redirect("Details.aspx");
        }
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username Or Password')</script>");
        }

let me know this works on not.. ? run the sp against your database..

As you asked for the stored procedure.. below is the one with OUTPUT parameter ..

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'proc_name')
BEGIN
DROP Procedure [dbo].[proc_name]
END

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO


/*
File Name : proc_name.sql
Description : 
Author : Vinay.T
Date :
*/

CREATE Procedure [dbo].[proc_name]
(
     @Username VarChar(50)
    ,@UPassword varChar(50)
    ,@OutRes int OUTPUT 
)
AS

BEGIN
SET NOCOUNT ON

DECLARE @ErrMsg NVARCHAR(510) --
        ,@ErrorSeverity INT --16 if business error
BEGIN

SET @OutRes = (SELECT count(*) FROM [dbo].Log_Users WHERE Username = @Username And [Password] = @UPassword)


END
GOTO SUCCESS

SUCCESS:
RETURN 1
CRASH:
RAISERROR (@ErrMsg, @ErrorSeverity, 1) WITH NOWAIT
END
GO
GRANT EXEC ON [dbo].[proc_name] TO PUBLIC

GO

============================================

execute the above sp and use the DataReader to fetch the Output parameter as suggested in the previous answer...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top