Tuesday, July 21, 2015

Insert Data into Database using Store procedure in Linq to sql

In this tutorial I will explain how to insert Data into Database using Store procedure in DLINQ ( Linq to Sql)


Implementation:
Create a table Tb_Student

Insert Data into Database using Store procedure in Linq to sql


Create a store procedure to insert data into database
Create Proc Sp_InsertStudents
(
@sname varchar(50),
@saddress varchar(200),
@rollno int
)
As begin
Insert into Tb_Student values(@sname,@saddress,@rollno)
end 

Add a webform to project/website. Drag and drop the required controls from toolbox to webform.
HTML Markup of webform:
  <table>
        <tr><td>Name :</td><td></td><td>
            <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td>Address :</td><td></td><td>
            <asp:TextBox ID="txtaddress" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr>
        <tr><td></td><td></td><td></td></tr>
        <tr><td>Roll Number :</td><td></td><td>
            <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox></td></tr>
        <tr><td></td><td></td><td>
            <asp:Button ID="btnsubmit" runat="server" Text="Submit"/></td></tr>
    </table>

Create object of ContextData file.
C#:
ProjectDataClassesDataContext db = new ProjectDataClassesDataContext();
VB:
Dim db As New ProjectDataClassesDataContext

Write the code on Submit button.
C#:
  protected void btnsubmit_Click(object sender, EventArgs e)
    {
        db.Sp_InsertStudents(txtname.Text, txtaddress.Text, Convert.ToInt32(txtrollno.Text));
        db.SubmitChanges();
        Response.Write("<script type=\"text/javascript\">alert('Data Insert Successfully');</script>");
        Clear();
    }
    private void Clear()
    {
        txtname.Text = "";
        txtaddress.Text = "";
        txtrollno.Text = "";
    }

VB:
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
        db.Sp_InsertStudents(txtname.Text, txtaddress.Text, Convert.ToInt32(txtrollno.Text))
        db.SubmitChanges()
        Response.Write("<script type=""text/javascript"">alert('Data Insert Successfully');</script>")
        Clear()
    End Sub
    Private Sub Clear()
        txtname.Text = ""
        txtaddress.Text = ""
        txtrollno.Text = ""
    End Sub

Now build, run the project and check out the result. 

  In this article we have learn How to insert data into database using Store Procedure in Linq (C#, VB). I hope you enjoyed this article. 

No comments:

Post a Comment