Create,Read,Update,Delete CRUD Operations using C#,Asp.Net,SQL Server Part 3

Bangalore: Hi Friends those who are not checked the part 1 and part 2 articles please go through it. because its continuation from that.
Part 1
Part 2
Here we are going to explain about Search and Delete operations.
First we will fetch all data from the corresponding table and on button click we will bind those data into the grid view. and there we have provided a radio button and a Delete button you can select your raw using radio button and on delete button click it will delete that row.
So design your form like this two buttons and a gridview.
For selecting only one raw at a time we have used a java script.
check the code for Delete.aspx page

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

<!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 runat="server">
    <title>Delete</title>
    <script language="javascript" type="text/javascript">
        function SelectSingleRadiobutton(rdbtnid) {
            var rdBtn = document.getElementById(rdbtnid);
            var rdBtnList = document.getElementsByTagName("input");
            for (i = 0; i < rdBtnList.length; i++) {
                if (rdBtnList[i].type == "radio" && rdBtnList[i].id != rdBtn.id) {
                    rdBtnList[i].checked = false;
                }
            }
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button id="btnFill" Text="Fill" runat="server" onclick="btnFill_Click" />
    <asp:Button id="btnDelete" Text="Delete" runat="server" onclick="btnDelete_Click"/>
    </div>
    <div>
     <div>
    <asp:GridView runat="server" ID="gdvSearch" DataKeyNames="id"
    AutoGenerateColumns="false" PageSize="6" BackColor="White"  Width="100%"
    BorderColor="Black" BorderStyle="Ridge" BorderWidth="2px" CellPadding="8" CellSpacing="1"
     ForeColor="#330199" GridLines="None" HeaderStyle-BorderColor="Black"
            RowStyle-BackColor="White" >
     <Columns>
     <asp:TemplateField ItemStyle-Width="50px" >
     <ItemTemplate>
     <asp:RadioButton ID="rdgridselect" runat="server" OnClick="javascript:SelectSingleRadiobutton(this.id)"/>
     </ItemTemplate>

     </asp:TemplateField>
     <asp:BoundField DataField="username" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="100px"  HeaderText="User Name" >
     </asp:BoundField>

     <asp:BoundField DataField="email" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="100px" ReadOnly="true" HeaderText="email">
     </asp:BoundField>
     <asp:BoundField DataField="company" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="100px" ReadOnly="true" HeaderText="company" ></asp:BoundField>

     <asp:BoundField DataField="mobile" HeaderStyle-HorizontalAlign="Left" ItemStyle-Width="100px" ReadOnly="true" HeaderText="mobile" ></asp:BoundField>
     
     </Columns>

    </asp:GridView>
    </div>
    </div>
    </form>
</body>
</html>

So In code behind on Fill button click we will fetch all data and Bind it with our GridView.
an on button delete click we will get the ID from grid view we have declared DataKeyNames="id"
in our gridview so we will get corresponding id as per the radio button click.
Check the code behind Aspx.cs code.

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.IO;

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

        }
        public string getConstring()
        {
            string constr = ConfigurationManager.ConnectionStrings["constrng"].ConnectionString;
            return constr;
        }

        protected void btnFill_Click(object sender, EventArgs e)
        {
            string str = getConstring();
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("Select * from crud", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                gdvSearch.DataSource = dt;
                gdvSearch.DataBind();
                ViewState["file"] = dt;

            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gdvSearch.Rows)
            {
                if (((CheckBox)row.FindControl("rdgridselect")).Checked)
                {

                    int id = Convert.ToInt32(gdvSearch.DataKeys[row.RowIndex].Value);
                    string str = getConstring();
                    SqlConnection con = new SqlConnection(str);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("delete from crud where id=" + id, con);
                    int result = cmd.ExecuteNonQuery();
                    if (result == 1)
                    {
                        SqlCommand cmds = new SqlCommand("Select * from crud", con);
                        SqlDataAdapter da = new SqlDataAdapter(cmds);
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        gdvSearch.DataSource = dt;
                        gdvSearch.DataBind();
                    }
                }
            }
        }
    }
}


Please write to us If you are not able to understand any part of our code..

Create,Read,Update,Delete CRUD Operations using C#,Asp.Net,SQL Server Part 2

Bangalore:Hi friends  Please check the part 1 for create operations Click
Create Table as explained in part 1.
Here we are going to discuss about Update as well as Search operations. so first we will enter a name in username field and on text changing we will search in database that is there any user with this name then it will fill all other details into text field and on submit button click you can do update operations.

So design your update form like this and disable all text fields other than username. Please go through the Update.Aspx page

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

<!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 runat="server">
    <title>Update</title>
    <script language="javascript" type="text/javascript">

        function empty() {
            document.getElementById("txtUserName").value = "";
            document.getElementById("txtEmail").value = "";
            document.getElementById("txtCompany").value = "";
            document.getElementById("txtMobile").value = "";
            return true;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <table width="500px">
    <tr class="width">
    <td nowrap="nowrap">UserName
    </td>
    <td><asp:TextBox ID="txtUserName" runat="server" 
            ontextchanged="txtUserName_TextChanged" AutoPostBack="true"></asp:TextBox></td>

    <td nowrap="nowrap">Email</td>
    <td><asp:TextBox ID="txtEmail" runat="server" Enabled="false"></asp:TextBox> </td>
    </tr>
    <tr class="width">
    
    <td nowrap="nowrap">CompanyName</td>
    <td><asp:TextBox ID="txtCompany" runat="server" Enabled="false"></asp:TextBox></td>
    <td nowrap="nowrap">Mobile</td>
    <td><asp:TextBox ID="txtMobile" runat="server" Enabled="false"></asp:TextBox></td>
    </tr>
    <tr>
    <td colspan="3" align="right"><asp:Button ID="btnSubmit" Text="Update" 
            runat="server" onclick="btnSubmit_Click" /> </td>
    <td><asp:Button ID="btnCancel" Text="Clear" runat="server"   OnClientClick="javascript:empty()"   CausesValidation="false"   /> </td>
    </tr>
    </table>
    </div>
    </form>
</body>
</html>


In code Behind we have one textchanged event and button click event. On text changing we will fill all data's as from db as per the username you have provided. and on update button click it will fire the update query.


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

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

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            string uname = txtUserName.Text;
            string email = txtEmail.Text;
            string comapany = txtCompany.Text;
            string Mobile = txtMobile.Text;
            string str = getConstring();
            SqlConnection con = new SqlConnection(str);
            con.Open();

            SqlCommand cmd = new SqlCommand("update  crud set email= '" + email + "',company='"+ comapany + "',mobile='"+Mobile+"'where username='" + uname +  "'", con);
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "showAlert", "alert('Data Updated Succesfully')", true);
                txtCompany.Text = "";
                txtEmail.Text = "";
                txtMobile.Text = "";
                txtUserName.Text = "";
                txtEmail.Enabled = false;
                txtMobile.Enabled = false;
                txtCompany.Enabled = false;
                txtUserName.Enabled = true;
            }

        }
        public string getConstring()
        {
            string constr = ConfigurationManager.ConnectionStrings["constrng"].ConnectionString;
            return constr;
        }

        protected void txtUserName_TextChanged(object sender, EventArgs e)
        {
            string str = getConstring();
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("Select username,email,company,mobile from crud where username='"+txtUserName.Text+"'", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
             
                txtEmail.Text = dt.Rows[0]["email"].ToString();
                txtMobile.Text = dt.Rows[0]["mobile"].ToString();
                txtCompany.Text = dt.Rows[0]["company"].ToString();
                txtEmail.Enabled = true;
                txtMobile.Enabled = true;
                txtCompany.Enabled = true;
                txtUserName.Enabled = false;
            }
        }
    }
}

Please go through the codes hope that you understood everything,write to us if you have any doubts.
About Delete Operations Part 3

Create,Read,Update,Delete CRUD Operations using C#,Asp.Net,SQL Server Part 1

Bangalore: Hi Friends In web application development most of the application must have to use Add,Update,Delete,Search operations.
Tools:Visual Studio 2010,SQL Server Management Studio
Create a New empty web project under c#.
add a Home.aspx page and other 4 WebForms for CRUD Operations. and Design your Home pag like this so that you can see all operation in home page itself.

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

<!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 runat="server">
    <title>CRUD</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="Create.aspx">Create</a>
    </div>
    <div>
    <a href="Read.aspx">Read</a>
    </div>
     <div>
    <a href="Update.aspx">Update</a>
    </div>
     <div>
    <a href="Delete.aspx">Delete</a>
    </div>
    </form>
</body>
</html>


CREATE
In this application we are going to discuss about Insertion or Creation operation Only.
So from Home page on Create Button click you will redirect into Create.Aspx Page.
Design your Create.aspx form like this.

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

<!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 runat="server">
    <title>Create</title>
    <style type="text/css">
    .width
    {
        height:40px;
    }
    </style>
   <script language="javascript" type="text/javascript">

       function empty() {
            document.getElementById("txtUserName").value = "";
            document.getElementById("txtEmail").value = "";
            document.getElementById("txtCompany").value = "";
            document.getElementById("txtMobile").value = "";
            return true;
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table width="500px">
    <tr class="width">
    <td nowrap="nowrap">UserName
    </td>
    <td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>

    <td nowrap="nowrap">Email</td>
    <td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> </td>
    </tr>
    <tr class="width">
 
    <td nowrap="nowrap">CompanyName</td>
    <td><asp:TextBox ID="txtCompany" runat="server"></asp:TextBox></td>
    <td nowrap="nowrap">Mobile</td>
    <td><asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td colspan="3" align="right"><asp:Button ID="btnSubmit" Text="Submit"
            runat="server" onclick="btnSubmit_Click" /> </td>
    <td><asp:Button ID="btnCancel" Text="Clear" runat="server"  OnClientClick="javascript:empty()"  CausesValidation="false"   /> </td>
    </tr>

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


So your Form Having username,email,company,mobile fields and corresponding textboxes for entering values on Submit button click you have to insert all these values into SQL Server Database. on clear Button click you have to clear all fields. For clearing all fields we have used a javascript.
So design a table in your SQL Server like this.

And in code behind write the logic for submit button click.
We are getting connection string from web.config file so declare connection string in one place no need to declare every where.
Add this connection string in web.config file after <system.web></system.web> tag

<connectionStrings >
    <add name="constrng" connectionString="Data Source=localhost; Initial Catalog=search; Integrated Security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Here In our code We have used Queries Inside our code itself for easy understanding. In real application development we will not write queries  inside our code. we will use stored procedures and we will call that procedures inside our code.
For easy learning purpose we have wrote the queries inside our code.
Please go through the Create.Aspx.cs code behind code.

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

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

        }
        public string getConstring()
        {
            string constr = ConfigurationManager.ConnectionStrings["constrng"].ConnectionString;
            return constr;
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            string uname = txtUserName.Text;
            string email = txtEmail.Text;
            string comapany = txtCompany.Text;
            string  Mobile = txtMobile.Text;
            string str = getConstring();
            SqlConnection con = new SqlConnection(str);
            con.Open();

            SqlCommand cmd=new SqlCommand("insert into crud(username,email,company,mobile) values('"+uname+"','"+email+"','"+comapany+"','"+Mobile+"')",con);
            int result=cmd.ExecuteNonQuery();
            if (result==1)
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "showAlert", "alert('Data Inserted Succesfully')", true);
                txtCompany.Text = "";
                txtEmail.Text = "";
                txtMobile.Text = "";
                txtUserName.Text = "";
            }
        }

    }
}
Please write to us If you are facing any difficulties.
In Part 2 we will describe about Update Operations. Part 2
In Part 3 we will describe about delete operations Part 3