Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Showing posts with label Stored Procedure. Show all posts
Showing posts with label Stored Procedure. Show all posts

Monday, 20 July 2015

Introduction:
In this article I will learn how to fill or populate Datatable using Stored Procedure with data from database in asp.net. First of we will fetch data from Sql database using Stored Procedure then  fill data in Dataset using SqlDataAdapter.


Implementation: Follow following steps
Create a database i.e. “Test”.  Then create a table “Student_Info”.
Column Name
Datatype
Student_id
Int(Primary Key. So set Is Identity=True)
Student_Name
Varchar(500)
Age
int
Class
Varchar(50)

Now insert some data in this table using “insert” command.
Create Stored Procedure:
create proc Fill_DataTable
as
begin
select * from student_info
end

Create Connection: Now create connection in  webconfig file as given below.
<connectionStrings>
    <add name="con" connectionString="Data Source=localhost; Initial Catalog= Blog; Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

ASP.NET code behind File using C#:

Add following Namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

C# Code to get data and Fill Data Table:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e) 
    {
        if (!IsPostBack)
        {
            Bind_datatable();
        }
    }
    //Fetch data from database and bind to gridview
public void    Bind_datatable ()
    {     
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        DataTable dt = new DataTable ();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Fill_ DataTable ";
        cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter dataadapater = new SqlDataAdapter();
    dataadapater.SelectCommand = cmd;
        dataadapater.Fill(dt);      
    }

VB.NET code:
Add following namespaces:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Now Write Following Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
        Bind_datatable()
    End If
End Sub
'Fetch data from database and fill dataset
Public Sub  Bind_datatable ()
    If con.State = ConnectionState.Open Then
        con.Close()
    End If
    con.Open()
    Dim dt As New DataTable ()
    Dim cmd As New SqlCommand()
    cmd.Connection = con
    cmd.CommandText = "Fill_DataTable"
    cmd.CommandType = CommandType.StoredProcedure
    Dim dataadapater As New SqlDataAdapter()
    dataadapater.SelectCommand = cmd
    dataadapater.Fill(dt)

End Sub
Introduction:
In this article I will explain how to fill or populate dataset using Stored Procedure  in asp.net. First of we will fetch data from Sql database using Stored Procedure then  fill data in Dataset using SqlDataAdapter.

Implementation: Follow following steps
Create a database i.e. “Test”.  Then create a table “Student_Info”.
Column Name
Datatype
Student_id
Int(Primary Key. So set Is Identity=True)
Student_Name
Varchar(500)
Age
int
Class
Varchar(50)

Now insert some data in this table using “insert” command.
Create Stored Procedure:
create proc Fill_DataSet
as
begin
select * from student_info

end

Create Connection: Now create connection in  webconfig file as given below.
<connectionStrings>
    <add name="con" connectionString="Data Source=localhost; Initial Catalog= Blog; Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

ASP.NET code behind File using C#:

Add following Namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

C# Code to get data and Fill Data Table:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e) 
    {
        if (!IsPostBack)
        {
            Fill_dataset();
        }
    }
    //Fetch data from database and bind to gridview
public void Fill_dataset()
    {     
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Fill_Dataset";
        cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter dataadapater = new SqlDataAdapter();
    dataadapater.SelectCommand = cmd;
        dataadapater.Fill(ds);      
    }

VB.NET code:
Add following namespaces:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Now Write Following Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
        Fill_dataset()
    End If
End Sub
'Fetch data from database and fill dataset
Public Sub Fill_dataset()
    If con.State = ConnectionState.Open Then
        con.Close()
    End If
    con.Open()
    Dim ds As New DataSet()
    Dim cmd As New SqlCommand()
    cmd.Connection = con
    cmd.CommandText = "Fill_Dataset"
    cmd.CommandType = CommandType.StoredProcedure
    Dim dataadapater As New SqlDataAdapter()
    dataadapater.SelectCommand = cmd
    dataadapater.Fill(ds)

End Sub

Tuesday, 10 March 2015

Introduction:  In this article I will explain how to upload the image through file upload control and save the image in website root folder and store the image path in Sql server database and then retrieve the record along with image according to image path and display in Gridview data control in asp.net using both C# and VB languages.
Introduction:  In this article I will explain how to upload the image through file upload control and save the image in website root folder and store the image path in Sql server database and then retrieve the record along with image according to image path and display in DataList data control in asp.net using both C# and VB languages. 

Monday, 9 March 2015

Introduction:  In this article I will explain how to upload the image through file upload control and save the image in website root folder and store the image path in Sql server database and then retrieve the record along with image according to image path and display in Repeater data control in asp.net using both C# and VB languages. 

Friday, 27 February 2015

We can validate and save data in database using jQuery, Ajax and Web-service method. jQuery ajax allows us to call server side ASP.NET page methods/functions declared as Web Method from client side without any postback. We make ajax call to web method using jQuery which contains the code to insert data in sql server.

In this article I am going to explain how to validate and save data into SQL SERVER database table in asp.net without any post back (asynchronously) using jQuery AJAX JSON and WebMethod.

Description:
Implementation: Let’s create a sample page to demonstrate the concept.
Create a datanbase in sql server  eg. “test”. Now create a table as given below:

CREATE TABLE [dbo].[Emp_Personal](
      [EmpPer_Id] [int] IDENTITY(1,1) NOT NULL,
      [EmpName] [varchar](100) NULL,
      [Age] [int] NULL,
      [Address] [varchar](500) NULL
) ON [PRIMARY]
In Web.config file create the connection string as: 
  <connectionStrings>
    <add name="EmpCon" connectionString="Data Source=localhost;Initial Catalog=test;Integrated Security=True"/>
  </connectionStrings>

Now create a stored procedure to save Employee Personal Details 

Create PROCEDURE [dbo].[SaveEmp_SP]
                @EmpName  VARCHAR(100),
              
                @age   INT,
                @Address  VARCHAR(500)
AS
BEGIN
                INSERT INTO dbo.Emp_Personal(EmpName,Age,Address)
                VALUES(@EmpName,@age,@Address)
END

Source Code:
Design Section:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">

        function SaveRecord() {
            //Get control's values
            var Name = $.trim($('#<%=txtName.ClientID %>').val());
            var age = $.trim($('#<%=txtAge.ClientID %>').val());
            var Address = $.trim($('#<%=txtAddress.ClientID %>').val());

            var msg = "";
            //check for validation
            if (Name == '') {
                msg += "<li>Please enter Employee name</li>";
            }
            if (age == '') {
                msg += "<li>Please enter Age</li>";
            }
            if (Address == 0) {
                msg += "<li>Please enter address</li>";
            }
            
            if (msg.length == 0) {
                //Jquery ajax call to server side method
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    //Url is the path of our web method (Page name/function name)
                    url: "MyPageName.aspx/SaveBookDetails",
                    //Pass paramenters to the server side function
                    data: "{'EmpName':'" +Name+ "', 'Age':'" +age+ "','Address':'" +Address+ "'}",
                    success: function (response) {
                        //Success or failure message e.g. Record saved or not saved successfully
                        if (response.d == true) {
                            //Set message
                            $('#dvResult').text("Record saved successfully");
                            //Reset controls                         
                            $('#txtName').val('');
                            $('#txtAge').val('');
                            $('#txtAddress').val("0");
                        }
                        else {
                            $('#dvResult').text("Record could't be saved");
                        }
                        //Fade Out to disappear message after 6 seconds
                        $('#dvResult').fadeOut(6000);
                    },
                    error: function (xhr, textStatus, error) {
                        //Show error message(if occured)
                        $('#dvResult').text("Error: " + error);
                    }
                });
            }
            else {
                //Validation failure message
                $('#dvResult').html('');
                $('#dvResult').html(msg);
            }
            $('#dvResult').fadeIn();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
    <td>Employee Name:</td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
 
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>      
    </tr>
  
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
                <tr>
                    <td></td>
                    <td>
                        <button type="submit" onclick="SaveRecord();return false">Submit</button>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <div id="dvResult"></div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


Asp.Net C# Code to validate and store data in sql server database table using jQuery Ajax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

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

    }
    [WebMethod]
    public static bool SaveEmpDetails(string Name, string age, Int32 Address)
    {
        bool status;

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Empcon"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SaveEmp_SP", con))
            {
               
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpName",Name);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@Address", Address);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                Int32 retVal = cmd.ExecuteNonQuery();
                if (retVal > 0)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                return status;
            }
        }
    }

}

Asp.Net VB Code to validate and store data in sql server database table using jQuery Ajax

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services

Partial Public Class Jquery_Insert
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub
    <WebMethod()> _
    Public Shared Function SaveEmpDetails(ByVal Name As String, ByVal age As String, ByVal Address As Int32) As Boolean
        Dim status As Boolean

        Imports (SqlConnection con = New SqlConnection(ConfigurationManager.ConnectionStrings("Empcon").ConnectionString))
        {
            Imports (SqlCommand cmd = New SqlCommand("SaveEmp_SP", con))
            {

        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@EmpName", Name)
        cmd.Parameters.AddWithValue("@age", age)
        cmd.Parameters.AddWithValue("@Address", Address)
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        Dim retVal As Int32 = cmd.ExecuteNonQuery()
        If retVal > 0 Then
            status = True
        Else
            status = False
        End If
        Return status
            }
        }
    End Function


End Class