Thursday, 3 August 2017

Insert, Delete, Update Using Entity Framework and LINQ in ASP.NET


1> Create Database First
2> Create Table

3> Add ADO.Net Entity Model in your project


4> Choose EFDesigner 



5> Click on connection and enter server name and choose database and click on OK.



6> Click on next button two times and you will get the properties of your table on the Page like


7> Add connectionstring on the web.config file.

web.config:-

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-insertdeleteupdateEFasp-20170801105050.mdf;Initial Catalog=aspnet-insertdeleteupdateEFasp-20170801105050;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="entityframeworkdemosEntities" connectionString="metadata=res://*/studentmodel.csdl|res://*/studentmodel.ssdl|res://*/studentmodel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=*****;initial catalog=entityframeworkdemos;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>


8> Add a form name studentdetails in your project


studentdetails.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="studentdetails.aspx.cs" Inherits="insertdeleteupdateEFasp.studentdetails" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <table>
           <tr>
               <td>
                   Name:
               </td>
               <td>
                   <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
               </td>
           </tr>
           <tr>
               <td>
                   Contact Number:
               </td>
               <td>
                   <asp:TextBox ID="txt_contact" TextMode="Number" runat="server"></asp:TextBox>
               </td>
           </tr>
            <tr>
               <td>
                   Address:
               </td>
               <td>
                   <asp:TextBox ID="txt_add" runat="server"></asp:TextBox>
               </td>
           </tr>

              <tr>
               <td>
                   Class:
               </td>
               <td>
                   <asp:TextBox ID="txt_class" runat="server"></asp:TextBox>
               </td>
           </tr>

                         <tr>
               <td>
                   Email:
               </td>
               <td>
                   <asp:TextBox ID="txt_email" runat="server"></asp:TextBox>
               </td>
           </tr>
              
             
       </table>
        <asp:Button ID="btn_submit" runat="server" Text="submit" OnClick="btn_submit_Click" />
    
    </div>
        

        <div style="margin-top:20px; margin-left:30%;">

            <asp:GridView ID="grvdtudentdetails" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField HeaderText="Id" DataField="id"/>
                    <asp:BoundField HeaderText="Name" DataField="name" />
                    <asp:BoundField HeaderText="Contact Number" DataField="contactnumber" />
                    <asp:BoundField HeaderText="Address" DataField="address" />
                    <asp:BoundField HeaderText="Class" DataField="class" />
                    <asp:BoundField HeaderText="Email" DataField="email" />
                    <asp:TemplateField HeaderText="Update">
                        <ItemTemplate>
                            <asp:Button ID="btn_update" runat="server" Text="Update" OnClick="btn_update_Click" CommandName='<%#Eval("id") %>'/>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate>
                            <asp:Button ID="btn_delete" runat="server" Text="Delete" OnClick="btn_delete_Click" CommandName='<%#Eval("id") %>' OnClientClick="return confirm('delete?')" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                
            </asp:GridView>

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

studentdetails.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace insertdeleteupdateEFasp
{
    public partial class studentdetails : System.Web.UI.Page
    {
        entityframeworkdemosEntities demo = new entityframeworkdemosEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
if(!IsPostBack)
            {
                studentdetailbind();
            }
            
        }
        public void studentdetailbind()
        {
            entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
            grvdtudentdetails.DataSource = demo1.studentoperations.ToList();
            grvdtudentdetails.DataBind();
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            entityframeworkdemosEntities demo = new entityframeworkdemosEntities();
            if (Session["id"] == null)
            {
                studentoperation sp = new studentoperation();
                sp.name = txt_name.Text;
                sp.contactnumber = txt_contact.Text;
                sp.address = txt_add.Text;
                sp.@class = txt_class.Text;
                sp.email = txt_email.Text;
                demo.studentoperations.Add(sp);
                demo.SaveChanges();
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validations", "alert('insert successfully')", true);
                txt_name.Text = ""; txt_contact.Text = ""; txt_add.Text = ""; txt_class.Text = ""; txt_email.Text = "";
            }
            else
            {
                entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
                studentoperation sp1 = new studentoperation();
                sp1.id = Convert.ToInt32(Session["id"]);
                sp1.name = txt_name.Text;
                sp1.contactnumber = txt_contact.Text;
                sp1.address = txt_add.Text;
                sp1.@class = txt_class.Text;
                sp1.email = txt_email.Text;
                demo1.Entry(sp1).State = System.Data.Entity.EntityState.Modified;
                demo1.SaveChanges();
                Session["id"] = null;
                txt_name.Text = ""; txt_contact.Text = ""; txt_add.Text = ""; txt_class.Text = ""; txt_email.Text = "";
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validations", "alert('Update successfully');window.location.href='../../../../studentdetails.aspx;", true);
                //Response.Redirect("~/studentdetails.aspx");
               
            }
        }

        protected void btn_update_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            int id = Convert.ToInt32(btn.CommandName);
            studentoperation sp = demo.studentoperations.Find(id);
            Session["id"] = sp.id;
            txt_name.Text = sp.name;
            txt_contact.Text = sp.contactnumber;
            txt_add.Text = sp.address;
            txt_class.Text = sp.@class;
            txt_email.Text = sp.email;
        }

        protected void btn_delete_Click(object sender, EventArgs e)
        {
            entityframeworkdemosEntities demo1 = new entityframeworkdemosEntities();
            Button btn = sender as Button;
            int id = Convert.ToInt32(btn.CommandName);
            studentoperation sp = demo1.studentoperations.Find(id);
            
            demo1.studentoperations.Remove(sp);
            demo1.SaveChanges();
            Response.Redirect("~/studentdetails.aspx");
        }
    }
}


Your Context class and Models are in the project after adding the ADO.net entity data model.
They will look under the folder like below snapshot:-













Thursday, 20 July 2017

Get Price in Textbox on Value change in Dropdown using HTML, Jquery and Javascript:-

Link Jquery file in your project:-


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="jquery-1.10.2.js"></script>

    <script>
        $(document).ready(function () {

            $("#ddl_cat").change(function () {
                debugger;  
                var a = document.getElementById("ddl_cat").value;
                if (a == "Burger")
                {
                    document.getElementById("txt_price").value = '200';
                }
                else if (a == "Cold Drink") {
                    document.getElementById("txt_price").value = '100';
                }


            });


        });
    </script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
        category:
   <select id="ddl_cat">
       <option>---select---</option>
       <option>Burger</option>
       <option>Cold Drink</option>
   </select>

        <br />
       Price:
        <input type="text" id="txt_price" />
    </div>
    </form>
</body>
</html>

Wednesday, 19 April 2017

Insert, Update, Delete Data in Grid View Using Asp Panel on a single form


Database:-


create table StudentDetails
(
Id int identity(1,1) primary key,
Name varchar(20),
contact varchar(15),
email varchar(50),
class varchar(10)
)

create proc insert_StudentDetails_sp
@Name varchar(20),
@contact varchar(15),
@email varchar(50),
@class varchar(10)
as
begin
insert into  StudentDetails(Name,contact,email,class) values(@Name,@contact,@email,@class)
end

select * from StudentDetails

create proc get_student_data
as
begin
select * from StudentDetails
end

create proc update_student_sp
@Id int,
@Name varchar(20),
@contact varchar(15),
@email varchar(50),
@class varchar(10)
as
begin
update StudentDetails set
Name=@Name,
contact=@contact,
email=@email,
class=@class
where Id = @Id
end

create proc delete_student_sp
@id int
as
begin
delete from StudentDetails where Id=@id
end





Web.Config File



<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="constr" value="Data source=*******; Initial catalog=******; user id=sa; password=*****;"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

BusinessLayer


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace GridViewPost
{
    public class BusinessLayer
    {
        string constring = ConfigurationManager.AppSettings["constr"].ToString();
        public void Add_Student(string name, string contact,string email,string student_class)
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("insert_StudentDetails_sp", con))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Name",name);
                cmd.Parameters.AddWithValue("@contact", contact);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@class", student_class);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        public DataTable get_Student_data()
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("get_student_data", con))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                adapt.Fill(dt);
                return dt;
            }
        }

        public void update_Student(int id,string name, string contact, string email, string student_class)
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("update_student_sp", con))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@contact", contact);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@class", student_class);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }

        public void delete_Student(int id)
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("delete_student_sp", con))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Id", id);
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }
}


StudentDetails.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentDetails.aspx.cs" Inherits="GridViewPost.StudentDetails" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Panel runat="server" ID="pnl_insertdata">
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Contact
                </td>
                <td>
                    <asp:TextBox ID="txt_contact" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Email
                </td>
                <td>
                    <asp:TextBox ID="txt_email" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Class
                </td>
                <td>
                    <asp:TextBox ID="txt_class" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>

                </td>
                <td>
                    <asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    </div>


         <div>
    <asp:Panel runat="server" ID="pnl_update_student">
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txt_up_name" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Contact
                </td>
                <td>
                    <asp:TextBox ID="txt_up_contact" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Email
                </td>
                <td>
                    <asp:TextBox ID="txt_up_email" runat="server"></asp:TextBox>
                </td>
            </tr>
             <tr>
                <td>
                    Class
                </td>
                <td>
                    <asp:TextBox ID="txt_up_class" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>

                </td>
                <td>
                    <asp:Button ID="btn_update" runat="server" Text="Update" OnClick="btn_update_Click" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    </div>


        <asp:HiddenField ID="hfid" runat="server" />

        <div>
            <asp:Panel runat="server" ID="pnl_grid">
                <asp:GridView ID="grd_st_data" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="grd_st_data_SelectedIndexChanged" OnRowDeleting="grd_st_data_RowDeleting">
                    <Columns>
                        <asp:BoundField HeaderText="Id" DataField="Id" />
                        <asp:BoundField HeaderText="Name" DataField="Name" />
                        <asp:BoundField HeaderText="Contact" DataField="contact" />
                        <asp:BoundField HeaderText="Email" DataField="email" />
                        <asp:BoundField HeaderText="Class" DataField="class" />
                        <asp:TemplateField HeaderText="Update">
                            <ItemTemplate>
                                <asp:Button ID="btn_update" runat="server" CommandName="Select" Text="Update"/>
                            </ItemTemplate>
                        </asp:TemplateField>
                          <asp:TemplateField HeaderText="Delete">
                            <ItemTemplate>
                                <asp:Button ID="btn_delete" runat="server" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Confirm Delete')" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </asp:Panel>
        </div>
    </form>
</body>
</html>


StudentDetails.aspx.cs



using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GridViewPost
{
    public partial class StudentDetails : System.Web.UI.Page
    {
        BusinessLayer objbusiness = new BusinessLayer();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                grid_bind();
            }
            pnl_insertdata.Visible = true;
            pnl_grid.Visible = true;
            pnl_update_student.Visible = false;
        }
        public void grid_bind()
        {
            DataTable dt = objbusiness.get_Student_data();
            grd_st_data.DataSource = dt;
            grd_st_data.DataBind();
        }
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string name = txt_name.Text;
            string contact = txt_contact.Text;
            string email = txt_email.Text;
            string st_class = txt_class.Text;
            objbusiness.Add_Student(name, contact, email, st_class);
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validation", "alert('Insert Successfully')", true);
            txt_name.Text="";
            txt_contact.Text="";
            txt_email.Text="";
            txt_class.Text="";
            grid_bind();
            pnl_update_student.Visible = false;
        }
        
        protected void grd_st_data_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow row = grd_st_data.SelectedRow;
            Session["id"] = row.Cells[0].Text;
            txt_up_name.Text = row.Cells[1].Text;
            txt_up_contact.Text = row.Cells[2].Text;
            txt_up_email.Text = row.Cells[3].Text;
            txt_up_class.Text = row.Cells[4].Text;
            pnl_insertdata.Visible = false;
            pnl_update_student.Visible = true;
            pnl_grid.Visible = true;
            grid_bind();
        }

        protected void btn_update_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(Session["id"]);
            string name = txt_up_name.Text;
            string contact = txt_up_contact.Text;
            string email = txt_up_email.Text;
            string st_class = txt_up_class.Text;
            objbusiness.update_Student(id,name, contact, email, st_class);
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "validation", "alert('Update Successfully')", true);
            pnl_update_student.Visible = false;
            grid_bind();
        }

        protected void grd_st_data_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = Convert.ToInt32(grd_st_data.Rows[e.RowIndex].Cells[0].Text);
            objbusiness.delete_Student(id);
            grid_bind();
            pnl_update_student.Visible = false;
        }
    }
}























Monday, 3 April 2017

Rahul Sharma: MVC 5

Rahul Sharma: MVC 5: CHAPTER-1 Web Applications:- Web Applications are programs that are executed on a web server and accessed from a web browser. ...

Sunday, 2 April 2017

Rahul Sharma: C#

Rahul Sharma: C#: Learn C# Console in short Chapter-1 What is Program? A Computer needs a set of instruction called a program to perform any opera...

Saturday, 18 March 2017

Insert Data on Server using Web Methods in Asp.Net


Database
Create a Table in Database

create table insert_user
(
id int primary key identity(1,1),
Name varchar(20),
contact_number varchar(20),
email varchar(20),
username varchar(10),
password varchar(10),
gender varchar(10),
country varchar(10)
)

Create Stored Procedure to insert data in table

create proc insert_sp_user
@Name varchar(20),
@contact_number varchar(20),
@email varchar(20),
@username varchar(10),
@password varchar(10),
@gender varchar(10),
@country varchar(10),
@success int out
as
begin
insert into insert_user(Name,contact_number,email,username,password,gender,country) values(@Name, @contact_number, @email, @username, @password,@gender,@country)
end




Web.Config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="constr" value="Database=******; Initial catalog=*****; user id=*****; password=*****;"/>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>


BusinessLayer

Add a class with the name BusinessLayer.

 public class BusinessLayer
    {
        string constring = ConfigurationManager.AppSettings["constr"].ToString();
        public int Add_user(string name,Int64 contact,string email,string username, string password,string gender, string country)
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("insert_sp_user", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter outputvalue = new SqlParameter("@success", SqlDbType.Int);
                outputvalue.Direction = ParameterDirection.Output;
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@contact_number", contact);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                cmd.Parameters.AddWithValue("@gender", gender);
                cmd.Parameters.AddWithValue("@country", country);
                cmd.Parameters.Add(outputvalue);
                con.Open();
                cmd.ExecuteNonQuery();
                int result = 1;
                if (outputvalue.Value != DBNull.Value)
                    result = Convert.ToInt32(outputvalue.Value);
                return result;
            }
        }
    }

User.aspx



Add a web frm with the name User
Insert Jquery reference on the form.


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=btn_submit.ClientID%>").click(function () {
                debugger;
                var name = $("#<%=txt_name.ClientID%>").val();
                var contact = $("#<%=txt_contact.ClientID%>").val();
                var email = $("#<%=txt_email.ClientID%>").val();
                var username = $("#<%=txt_username.ClientID%>").val();
                var password = $("#<%=txt_password.ClientID%>").val();
                var gender = "";
                if ($("#<%=rdbmale.ClientID%>").is(":checked"))
                    gender = "Male";
                else
                    gender = "Female";

                var country = $("#<%=ddl_country.ClientID%> option:selected").text();
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "User.aspx/user_insertion",
                    data: '{"name":"' + name + '","contact":"' + contact + '","email":"' + email + '","username":"' + username + '","password":"' + password + '","gender":"' + gender + '","country":"' + country + '"}',
                    dataType: "json",
                    success: function (data) {
                        debugger;
                        alert("Insert Successfully");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table>
            <tr>
                <td>

               
    <asp:Label ID="lbl_name" Text="Name" runat="server">
    </asp:Label>
                    </td>
                <td>
        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfv_name" runat="server" ControlToValidate="txt_name" ErrorMessage="Enter Name Please"></asp:RequiredFieldValidator>
                     </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lbl_contact" runat="server" Text="Contact Number"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txt_contact" runat="server" TextMode="Number"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfv_contact" runat="server" ControlToValidate="txt_contact" ErrorMessage="Enter Contact Number"></asp:RequiredFieldValidator>
                </td>
            </tr>
          <tr>
                <td>

               
    <asp:Label ID="lbl_email" Text="Email Address" runat="server">
    </asp:Label>
                    </td>
                <td>
        <asp:TextBox ID="txt_email" runat="server" TextMode="Email"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfv_email" runat="server" ControlToValidate="txt_email" ErrorMessage="Enter Email Address Please"></asp:RequiredFieldValidator>
                     </td>
            </tr>
         <tr>
                <td>

               
    <asp:Label ID="lbl_username" Text="User Name" runat="server">
    </asp:Label>
                    </td>
                <td>
        <asp:TextBox ID="txt_username" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfv_username" runat="server" ControlToValidate="txt_username" ErrorMessage="Enter UserName Please"></asp:RequiredFieldValidator>
                     </td>
            </tr>
          <tr>
                <td>

               
    <asp:Label ID="lbl_password" Text="Password" runat="server">
    </asp:Label>
                    </td>
                <td>
        <asp:TextBox ID="txt_password" runat="server" TextMode="Password"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfv_password" runat="server" ControlToValidate="txt_password" ErrorMessage="Enter password Please"></asp:RequiredFieldValidator>
                     </td>
            </tr>
         <tr>
                <td>
                    <asp:Label ID="lbl_gender" runat="server" Text="Gender"></asp:Label>
                </td>
                <td>
                    <asp:RadioButton ID="rdbmale" runat="server" Text="Male" GroupName="Gender" Checked="true" />
                    <asp:RadioButton ID="rdb_female" runat="server" Text="Female" GroupName="Gender" />
                </td>
            </tr>
          <tr>
                <td>
                    <asp:Label ID="lbl_state" runat="server" Text="State"></asp:Label>
                </td>
                <td>
                    <asp:DropDownList ID="ddl_country" runat="server">
                        <asp:ListItem>India</asp:ListItem>
                        <asp:ListItem>USA</asp:ListItem>
                        <asp:ListItem>Newzeland</asp:ListItem>
                        <asp:ListItem>UK</asp:ListItem>
                        <asp:ListItem>Sri Lanka</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
          <tr>
                <td></td>
                <td>
                    <asp:Button ID="btn_submit" runat="server" Text="Submit"/>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


User.aspx.cs

Add namespace for the web [WebMethod] using System.Web.Services;


 [WebMethod]
        public static string user_insertion(string name, Int64 contact,string email,string username, string password, string gender,string country)
        {
            BusinessLayer objbusiness = new BusinessLayer();
            string status = "true";
            int result = objbusiness.Add_user(name, contact, email, username, password, gender, country);
            if(result==0)
            {
                status = "false";
            }
            return status;
        }







Thursday, 16 March 2017

Bind Data in DropDown Dynamically using Web Methods in Asp.Net

Database


1> Create a Table in SQL with the name country.
2> Insert atleast 5 country name within the table.
3>Create a stored procedure with the name

Create proc country_bind_sp
as
begin
select id,country from country
end


Web.Config File

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="constr" value="Data source=*****;Initial catalog=*****; user id=*****; password=*****;"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>




Business Layer

Create a class with the name BusinessLayer to write the ADO Code.


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace DropDownBind
{
    public class BusinessLayer
    {
        string constring = ConfigurationManager.AppSettings["constr"].ToString();
        public DataTable countrybind()
        {
            using (SqlConnection con = new SqlConnection(constring))
            using (SqlCommand cmd = new SqlCommand("country_bind_sp", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                adapt.Fill(dt);
                return dt;
            }
        }
    }
}


Web Form

ADD Web Form in Project with the name Country

Country.Aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Country.aspx.cs" Inherits="DropDownBind.Country" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.min.js"></script>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            binding();
        });

        function binding()
        {
            debugger
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Country.aspx/BindCountry",
                data: "{}",
                dataType: "json",
                success: function (data) {
                    debugger;
                        $("#<%=ddl_country.ClientID %>").append($("<option></option>").val(0).html("-Select SubCategory-"));
                    $.each(data.d, function (key, value) {
                        $("#<%=ddl_country.ClientID %>").append($("<option></option>").val(value.DataValueField).html(value.DataTextField));
                    });
                },
                error: function (result) { }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddl_country" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>


Country.Aspx.cs


  [WebMethod]
        public static Country1[] BindCountry()
        {
            List<Country1> cntry = new List<Country1>();
            BusinessLayer objbusiness = new BusinessLayer();
            DataTable dt = objbusiness.countrybind();
           for(int i=0;i<dt.Rows.Count;i++)
            {
                Country1 cont = new Country1();
                cont.DataValueField = Convert.ToInt32(dt.Rows[i]["id"]);
               cont.DataTextField = dt.Rows[i]["country"].ToString();
                cntry.Add(cont);
            }
            return cntry.ToArray();
        }

       
    }
    public class Country1
    {
        public int DataValueField { get; set; }
        public string DataTextField { get; set; }
    }
}

If you have any query please post in the comment
                                                                       sharmarahulsoftwareengineer.blogspot.in

Insert, Delete, Update Using Entity Framework and LINQ in ASP.NET 1> Create Database First 2> Create Table 3> Add ADO...