Wednesday, 13 November 2013

grid through database insert update and delete in c#

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;
using System.Data.SqlClient;

public partial class gridtodatabaseinserupdatedelete : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
     DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {

        //table gridsalary field id,name,age

       // id name  age
        //1    abc       5
        //2    def       8
        //3    ghi       56
        //insert update delete through gridview to database

        if (IsPostBack == false)
        {
            Session.Remove("dt_Session");
            if (cn.State == ConnectionState.Closed)
                cn.Open();
         
            SqlCommand cmd = new SqlCommand("select * from gridsalary", cn);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                Session["dt_Session"] = dt;
                GrdBind();
            }

            cn.Close();

        }
    }

    private void bind()
    {
      
        if (cn.State == ConnectionState.Closed)
            cn.Open();

        SqlCommand cmd = new SqlCommand("select * from gridsalary", cn);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);

        if (ds.Tables.Count > 0)
        {
            dt = ds.Tables[0];
            Session["dt_Session"] = dt;
            GrdBind();
        }

        cn.Close();
    }

    protected void btnadd_Click(object sender, EventArgs e)
    {
        if (txtname.Text.Trim() != String.Empty && txtage.Text.Trim() != String.Empty)
        {
            if (btnadd.Text == "Update")//update newrows and available rows
            {
             
                if (Session["dt_Session"] != null)
                {
                    dt = (DataTable)Session["dt_Session"];
                }
                else
                {
                    dt = new DataTable();
                    dt.Columns.Add("ID");
                    dt.Columns.Add("NAME");
                    dt.Columns.Add("AGE");
                }
                Int32 Id = 1;
                if (dt != null && dt.Rows.Count > 0)
                {
                    //session rowindex display rowindex position
                    if(Session["RowIndex"]!="")
                    Id = Convert.ToInt32(Session["RowIndex"])-1 ;
                    else
                        Id = Convert.ToInt32(Session["RowIndex"]);
                }


                DataRow drow;
                drow = dt.NewRow();
                //check click edit button or not
                if (Session["RowIndex"] != "" || Session["RowIndex"]=="0")
                    drow[0] = ViewState["id"];//view state display  id field data of rowindex
                else
                    drow[0] = Id + 1;
                if (cn.State == ConnectionState.Closed)
                    cn.Open();
                string sql="select count(id) from gridsalary where id='"+drow[0]+"'";
                SqlCommand cmd=new SqlCommand (sql,cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
              
                if(ds.Tables[0].Rows.Count>0)
                {
                 
          
                    drow[1] = txtname.Text;
                    drow[2] = txtage.Text;
                  
                    dt.Rows[Id]["name"] = drow[1];
                    dt.Rows[Id]["age"] = drow[2];
                 
                    cn.Close();
                }

                else
                {
                    drow[1] = txtname.Text;
                    drow[2] = txtage.Text;
                    dt.Rows.RemoveAt(Id);
                    dt.Rows.InsertAt(drow, Id);
                }
                Session.Add("dt_Session", dt);
               // dt.Rows[0].SetModified();
                GrdBind();
                ClearTextBoxes();
                lbstatus.Text = "Data Updated Successfully";
                btnadd.Text = "Add";
            }
            else  //added new rows
            {
                DataTable dt;
                if (Session["dt_Session"] != null)
                {
                    dt = (DataTable)Session["dt_Session"];
                }
                else
                {
                    dt = new DataTable();
                    dt.Columns.Add("ID");
                    dt.Columns.Add("NAME");
                    dt.Columns.Add("AGE");
                }
                Int32 Id = 1;
                if (dt != null && dt.Rows.Count > 0)
                {
                    Id = dt.Rows.Count + 1;
                }
                DataRow drow;
                drow = dt.NewRow();
                drow[0] = Id;
                drow[1] = txtname.Text;
                drow[2] = txtage.Text;
                dt.Rows.Add(drow);
                Session.Add("dt_Session", dt);

                GrdBind();
                ClearTextBoxes();
                lbstatus.Text = "Data Added Successfully";
            }
        }
        else
        {
            lbstatus.Text = "Enter Name and Age";
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditRow")
        {
            foreach (DataRow drow in ((DataTable)Session["dt_Session"]).Rows)
            {
                Int32 RowIndex = 0;
                foreach (DataRow _drow in ((DataTable)Session["dt_Session"]).Rows)
                {
                    if (Convert.ToInt32(_drow["ID"]) == Convert.ToInt32(e.CommandArgument))
                    {
                        RowIndex = Convert.ToInt32(e.CommandArgument);
                        //btnadd.CommandArgument = RowIndex.ToString();
                        txtname.Text = Convert.ToString(_drow["NAME"]);
                        txtage.Text = Convert.ToString(_drow["AGE"]);
                        btnadd.Text = "Update";
                        ViewState["id"] = _drow["ID"];
                        Session["RowIndex"] = RowIndex;
                        goto endPoint;
                     
                    }
                    RowIndex += 1;
                }
            endPoint: GrdBind();
            }
        }
        else if (e.CommandName == "DeleteRow")
        {
            Int32 RowIndex = 0;
            foreach (DataRow drow in ((DataTable)Session["dt_Session"]).Rows)
            {
                if (Convert.ToInt32(drow["ID"]) == Convert.ToInt32(e.CommandArgument))
                {
                  
                    //((DataTable)Session["dt_Session"]).Rows.RemoveAt(RowIndex);
                    ((DataTable)Session["dt_Session"]).Rows[RowIndex].Delete();
                
                    goto endPoint;
                  
                }
                RowIndex += 1;
            }
        endPoint:
            GrdBind();
            ClearTextBoxes();
            btnadd.Text = "Add";
        }
    }

    private void GrdBind()
    {
        GridView1.DataSource = (DataTable)Session["dt_Session"];
        GridView1.DataBind();
    }

    private void ClearTextBoxes()
    {
        txtname.Text = String.Empty;
        txtage.Text = String.Empty;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      
      
    
        int i;
        dt = (DataTable)Session["dt_Session"];
        foreach (DataRow dr in dt.Rows)
        {
            if (dr.RowState == DataRowState.Added)
            {
              
                int id = Convert.ToInt32(dr[0]);
                string sal = dr[1].ToString();
                int age = Convert.ToInt32(dr[2]);
                ////for (i = 0; i < GridView1.Rows.Count; i++)
                ////{
                // string s = GridView1.Rows[i].Cells[0].Text;
               if(cn.State==ConnectionState.Closed)
                cn.Open();
               SqlCommand cmd = new SqlCommand("insert into gridsalary values('"+id+"','" + sal + "','"+age+"')", cn);
                cmd.ExecuteNonQuery();
                cn.Close();

                lbstatus.Text = "Data Added Successfully";
                bind();
                //}

            }

            else  if (dr.RowState == DataRowState.Modified)
            {
                int id = Convert.ToInt32(dr[0]);
                string sal = dr[1].ToString();
                int age = Convert.ToInt32(dr[2]);
                ////for (i = 0; i < GridView1.Rows.Count; i++)
                ////{
                // string s = GridView1.Rows[i].Cells[0].Text;
                if (cn.State == ConnectionState.Closed)
             
                cn.Open();
                SqlCommand cmd = new SqlCommand("update gridsalary set name='" + sal + "' , age='"+age+"' where id='"+id+"' " , cn);
                cmd.ExecuteNonQuery();
                cn.Close();

                lbstatus.Text = "Data updated Successfully";
                bind();
                //}

            }
            else  if (dr.RowState == DataRowState.Deleted)
            {
              
              
              
                int id = Convert.ToInt32(dr[0, DataRowVersion.Original].ToString());
              
                if (cn.State == ConnectionState.Closed)

                    cn.Open();
                SqlCommand cmd = new SqlCommand("delete  from gridsalary  where id='"+id+"' ", cn);
                cmd.ExecuteNonQuery();
                cn.Close();

                lbstatus.Text = "Data deleted Successfully";
                bind();
                //}

            }

          

          
        }
    }

  
}

//.aspx page



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

<!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>Temporary DataTable Operations</title>
</head>
<body>
<form id="Form1" runat="server">
<asp:Label ID="lbstatus" runat="server" />
Name: <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
Age: <asp:TextBox ID="txtage" runat="server"></asp:TextBox>
<asp:Button ID="btnadd" Text="Add" OnClick="btnadd_Click" runat="server"></asp:Button>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" DataKeyNames="ID" OnRowCommand="GridView1_RowCommand" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>Id</HeaderTemplate>
<ItemTemplate><%#Eval("ID") %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Name</HeaderTemplate>
<ItemTemplate><asp:Label ID="lbname" Text='<%#Eval("NAME") %>' runat="server" /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Age</HeaderTemplate>
<ItemTemplate><asp:Label ID="lbage" Text='<%#Eval("AGE") %>' runat="server" /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate><asp:LinkButton ID="btnedit" Text="Edit" CommandName="EditRow" CommandArgument='<%#Eval("ID") %>' runat="server" /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate><asp:LinkButton ID="btndelete" Text="Delete" CommandName="DeleteRow" CommandArgument='<%#Eval("ID") %>' runat="server" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div>

    <asp:Button ID="Button1" runat="server" Text="submit" onclick="Button1_Click" />
</div>
</form>
</body>
</html>