Monday, 14 November 2016

Handle dopostback in i.e.

put this code in master page
 protected override void OnInit(EventArgs e)
        {
            Page.ClientTarget = "uplevel";
            base.OnInit(e);

        }

Thursday, 3 March 2016

custom paging with searching

//Pass FirstRec ,CurrentPage ,PageSize ,LastRec,OrderBy,OrderByType   parameter through .Net

declare @total int  //count total row
Declare @FirstRec int
 declare @CurrentPage int
declare  @PageSize int
Declare @LastRec int

Set @FirstRec = (@CurrentPage - 1) * @PageSize
Set @LastRec = (@CurrentPage * @PageSize + 1)


IF(@OrderBy = '' or @OrderBy = 'Default')  
BEGIN  
 set @OrderBy = 'mpv.VisitDate '  
 set @OrderByType='desc'
 END

exec ( '
SELECT * FROM
(


SELECT  ROW_NUMBER() OVER (ORDER BY ' +  @OrderBy + ' ' + @OrderByType + ') AS RowNum,
               mp.PatientID,mp.FirstName+'' '' +mp.LastName + case when mp.MobileNumber <>''''  then  ''/ '' + mp.mobilenumber else ''''  END Name , convert(varchar(10),mpv.VisitDate,103)VisitDate,mpv.PatientVisitID,(select count(*) from     MDTM_Patient mp left JOIN MDTM_Patient_VisitDetail mpv on mp.PatientID=mpv.PatientID
                where  mp.IsDeleted=0 and mp.CreatedBy='+@LoginUserId +')as totalpatient,mc.ConsultationType,convert(varchar(10),mc.SentForReviewOn,103)SentForReviewOn,mu.FirstName +'' ''+ mu.LastName as Referto,mc.CaseStatus
             
            FROM MDTM_Patient mp left JOIN MDTM_Patient_VisitDetail mpv on mp.PatientID=mpv.PatientID left join MDTM_Patient_Consultation mc  on mpv.PatientID=mc.PatientID and mc.isdeleted=0 left join MDTM_Users mu on mc.ReferredToDoctor=mu.UserID and mu.IsDeleted=0
                where  mp.IsDeleted=0 and mp.CreatedBy='+@LoginUserId +'   and
(
             mp.FirstName like  '''+ @search+ '%'' or mp.LastName like  '''+ @search+ '%'' or
             mp.FirstName+'' ''+mp.LastName LIKE '''+ @search+ '%'' OR
             mu.FirstName like  '''+ @search+ '%'' or mu.LastName like  '''+ @search+ '%'' OR
             mu.FirstName+'' ''+mu.LastName LIKE '''+ @search+ '%'' OR
             mc.CaseStatus LIKE  '''+ @search+ '%'' OR
             CONVERT(varchar,mpv.VisitDate,105)= '''+ @search+ ''' OR
             CONVERT(varchar,mc.SentForReviewOn,105)= '''+ @search+ '''
             )
) records
where records.RowNum>' + @FirstRec  + ' and records.RowNum<  '+@LastRec )

Monday, 9 November 2015

how to create and use table variable

create User Defined Table type in Programmability in sql
my table type is 


1)    CREATE TYPE [dbo].[sitenamelist] AS TABLE(
[siteid] [int] NULL,
[Userid] [int] NULL,
[isdeleted] [bit] NULL,
[createdby] [int] NULL,
[modifiedby] [int] NULL
)

2) calll table type in storedprocedure
 @sitelist as sitenamelist READONLY

INSERT INTO MDTM_AdminSiteLink (SiteID,UserId,IsDeleted,[DateCreated], [CreatedBy]) select SiteID,Userid,isdeleted,GETDATE(),CreatedBy from sitenamelist


3)pass parameter in data layer
 comd.Parameters.AddWithValue("@sitelist", sitelist);

create get set DataTable Type in business entity
private DataTable _sitelist;
        public DataTable sitelist
        {
            get { return _sitelist; }
            set { _sitelist = value; }
        }

dynamic sub query with stuff


  1.  Here MDTM_Site  and MDTM_Hierarchy  is a table
  2. create #temphierachy   temporary table
  3. stuff use for comma seprated value in one row sitename wise




select ms.SiteID ,ms.sitename, mh.LinkedToSite as linksite,
(select SiteName from MDTM_Site where siteid=mh.linkedtosite) as LinkedSiteName
into #temphierachy
from MDTM_Hierarchy mh join MDTM_Site ms on mh.SiteID=ms.SiteID
where mh.NetworkID=@NetworkId and mh.IsDeleted=0

      select distinct sitename, siteid ,
        STUFF((SELECT distinct ', ' + LinkedSiteName
         FROM #temphierachy where sitename = t.sitename
       
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(255)')
        ,1,1,'')  AS LinkSiteName
       
      from #temphierachy t order by t.sitename DESC

Writting common Dataaccess layer for MYSQL, Oracle and SQL server by using enterprise library

Wednesday, 21 October 2015

Encrypt Decrypt ConnectionString in Web.Config

http://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config?loginkey=false

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
ASPNET_REGIIS -pef "connectionStrings" "D:\Articles\EncryptWebConfig" use this command
here EncryptWebConfig is project name
for decrypt 
ASPNET_REGIIS -pdf "connectionStrings" "D:\Articles\EncryptWebConfig" use this command

Thursday, 9 July 2015

Wednesday, 17 June 2015

ssis

http://mirror.dorkfolio.net/Books/SQL/SSIS%20Integration.pdf

Friday, 8 August 2014

update multiple rows single query sql server

declare @SymptomID int=46

update MD_RS_SymptomsReviewQuestions
 set Sequence = bb.Number
 from MD_RS_SymptomsReviewQuestions
 join
 (

select a.* --ROW_NUMBER() over (ORDER BY id) AS Number
from MD_RS_SymptomsReviewQuestions a
where a.SymptomID = @SymptomID
and a.IsDeleted = 0
and a.Sequence <= 0
 )aa
 on aa.ID = MD_RS_SymptomsReviewQuestions.ID
 join
 (
select b.ID, ROW_NUMBER() over (ORDER BY id) AS Number
from MD_RS_SymptomsReviewQuestions b
where b.SymptomID = @SymptomID
and b.IsDeleted = 0
and b.Sequence <= 0
 )bb
 on bb.ID = aa.ID

Wednesday, 22 January 2014

TextboxDataAdd in Gridview Through Database Using Linq in .Net

using System;
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.Collections.Generic;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
//linq class empdatacontext
//table emp

    empDataContext ee = new empDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["data"] = null;
            if (Session["data"] == null)
            {
                List<emp> emp = new List<emp>();

                GridView1.DataSource = ee.emps.ToList();
                GridView1.DataBind();

            }
            else
            {
                GridView1.DataSource = ee.emps.ToList();
                GridView1.DataBind();

            }
        }
    }
//add in grid
    protected void Button1_Click(object sender, EventArgs e)
    {
        emp em = new emp();
        var v=ee.emps.ToList();
        if (Session["data"] == null)
        {
            em.name = txtname.Text;
            em.address = txtaddress.Text;
            ee.emps.InsertOnSubmit(em);

             v = ee.emps.ToList();
            v.Add(em);
            GridView1.DataSource = v.ToList();
            GridView1.DataBind();
            Session["data"] = v;
            txtname.Text = "";
            txtaddress.Text = "";
        }
        else
        {
            List<emp> k = new List<emp>();
           
            k = (List<emp>)Session["data"];
            em.name = txtname.Text;
            em.address = txtaddress.Text;
            ee.emps.InsertOnSubmit(em);

            //k = ee.emps.ToList();
            k.Add(em);
            GridView1.DataSource = k.ToList();
            GridView1.DataBind();
            Session["data"] = k;

            txtname.Text = "";
            txtaddress.Text = "";



        }
    }
//final submit
    protected void Button2_Click(object sender, EventArgs e)
    {
       
        emp em1 = new emp();
       // var kk = k.ToList();
        var products = ee.emps.ToList();
        ee.emps.DeleteAllOnSubmit(products);
        ee.SubmitChanges();
   


//k = (List<emp>)Session["data"];
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            emp em = new emp();
            em.name = GridView1.Rows[i].Cells[0].Text.ToString();
            em.address = GridView1.Rows[i].Cells[1].Text.ToString();

            ee.emps.InsertOnSubmit(em);
            ee.SubmitChanges();
          
        }
       


        GridView1.DataSource = ee.emps.ToList();
            GridView1.DataBind();

        Session["data"] = null;
        txtname.Text = "";
        txtaddress.Text = "";


    }
}

Sunday, 12 January 2014

Learn Mvc3 (insert ,update ,delete using edmx with mvc)

http://www.pluralsight.com/training/Courses/TableOfContents/aspdotnet-mvc3-intro
http://www.w3schools.com/aspnet/mvc_intro.asp
http://malathyluxman.blogspot.in/2010/10/aspnet-mvc-viewcreate-edit-delete.html?showComment=1389597381543#c375097420805422145
http://www.c-sharpcorner.com/UploadFile/cd3310/createeditdelete-operation-on-a-table-in-Asp-Net-mvc-appli/





       First Create Edmx for connect with database
     second create controller
  ex:right click controller and add new controller  here i use employeeController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/



       
        CompanyEntities _db = new CompanyEntities(); //object of entity class
      
        public ActionResult Index()
        {
            return View(_db.Employees.ToList());
        }

        //
        // GET: /Employee/Details/5

        public ActionResult Details(Employee empdata)
        {
            var v = _db.Employees.ToList();
            return View(v);
        }

        //
        // GET: /Employee/reate

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        public ActionResult Create(Employee empData)
        {
            try
            {
                // TODO: Add insert logic here



                if (!ModelState.IsValid)
                    return View();
                _db.AddToEmployees(empData);
                _db.SaveChanges();
                return RedirectToAction("Index");
             
            }
            catch
            {
                return View();
            }
        }
       
        //
        // GET: /Employee/Edit/5

        public ActionResult Edit(int id)
        {
            var empToEdit = (from emp in _db.Employees where emp.ID.Equals(id) select emp).First();
            return View();
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        public ActionResult Edit(Employee empToEdit)
        {
            try
            {
                // TODO: Add update logic here

                var originalEmp = (from emp in _db.Employees where emp.ID.Equals(empToEdit.ID) select emp).First();
                if (!ModelState.IsValid)
                    return View(originalEmp);
                _db.ApplyPropertyChanges(originalEmp.EntityKey.EntitySetName, empToEdit);
                _db.SaveChanges();
                return RedirectToAction("Index");
              
           
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Employee/Delete/5

        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here

                var empToDelete = (from emp in _db.Employees where emp.ID.Equals(id) select emp).First();
                return View(empToDelete);


            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /Employee/Delete/5

        [HttpPost]
        public ActionResult Delete(int id,string s)
        {
            try
          {
             // var vv = _db.Employees.Where(a => a.ID == id).ToList();
          var originalEmp = (from emp in _db.Employees where emp.ID.Equals(id) select emp).First();
           _db.DeleteObject(originalEmp);
          _db.SaveChanges();
           return RedirectToAction("Index");
          }
          catch (Exception ex)
            {
                 return View();
            }
        
        }
    }
}


then create Employee floder in view
in employee create  index,create,edit,detail,delete.aspx (ex:right click employee and use first option view)
in view second dropdown use namespace.edmx.table name select

third box select create-if create,edit-if edit,list if index




ex:Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Employee>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>
                FirstName
            </th>
            <th>
                LastName
            </th>
            <th>
                ID
            </th>
            <th>
                Designation
            </th>
        </tr>

    <% foreach (var item in Model) { %>
   
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id=item.ID })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id=item.ID })%>
            </td>
            <td>
                <%: item.FirstName %>
            </td>
            <td>
                <%: item.LastName %>
            </td>
            <td>
                <%: item.ID %>
            </td>
            <td>
                <%: item.Designation %>
            </td>
        </tr>
   
    <% } %>

    </table>

    <p>
        <%: Html.ActionLink("Create New", "Create") %>
    </p>

</asp:Content>

//create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Employee>" %>



 

Tuesday, 31 December 2013

create rdlc report with report viewer

  1. http://www.aspsnippets.com/Articles/ASPNet-Report-Viewer-control-Tutorial-with-example.aspx
  2. http://www.c-sharpcorner.com/UploadFile/mahesh/ReportViewerIntro04042007100143AM/ReportViewerIntro.aspx
  3. http://www.codeproject.com/Articles/15597/Using-the-ASP-NET-2-0-ReportViewer-in-Local-Mode

rsitem not found in report server

Web.config


<system.web>
    <httpHandlers>
      <add verb=" * "
      path="Reserved.ReportViewerWebControl.axd" type =
        "Microsoft.Reporting.WebForms.HttpHandler,
        Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral,
        PublicKeyToken=b03f5f7f11d50a3a" />
    </httpHandlers>
    <compilation debug="true" targetFramework="4.0">

   
      <assemblies>
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
    </authentication>
    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>
    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
      </providers>
    </roleManager>
  </system.web>


ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
            ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver"); // Report Server URL
           //here report1.rdl in buissness intelligent report folder ReportProject1
            ReportViewer1.ServerReport.ReportPath = "/Report Project1/Report1"; // Report Name
            ReportViewer1.ShowParameterPrompts = false;
            ReportViewer1.ShowPrintButton = true;

            // Below code demonstrate the Parameter passing method. User only if you have parameters into the reports.
            ReportParameter[] param = new ReportParameter[1];
            param[0] = new ReportParameter("id", txtparam.Text);
            ReportViewer1.ServerReport.SetParameters(param);
            ReportViewer1.ServerReport.Refresh();

Friday, 27 December 2013

Translate website in multiple language

<div id='MicrosoftTranslatorWidget' class='Dark' style='color: white; background-color: #555555'>
    </div>
//use below javascript and above div tag
 <script type="text/javascript">
        setTimeout(function () { { var s = document.createElement('script'); s.type = 'text/javascript'; s.charset = 'UTF-8'; s.src = ((location && location.href && location.href.indexOf('https') == 0) ? 'https://ssl.microsofttranslator.com' : 'http://www.microsofttranslator.com') + '/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&from=en'; var p = document.getElementsByTagName('head')[0] || document.documentElement; p.insertBefore(s, p.firstChild); } }, 0);</script>

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>

Monday, 10 June 2013

row_number,dense_rank,delete duplicate value in sql


select * from emp
--OUTPUTS
id name  adddress
7    m     a
8    k     l
4    j     NULL
10    h     g
2    k     n
14    NULL mm
9    h      b
DELETE t FROM
(SELECT  id ,RANK() OVER(PARTITION BY name ORDER BY id DESC) AS rank,name FROM emp) AS t
WHERE t.rank <> 1

DELETE T FROM
(SELECT Row_Number() Over(Partition BY [Name] ORDER BY [ID]) AS RowNumber,* FROM emp)T
WHERE T.RowNumber > 1

DELETE
FROM emp
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM emp
GROUP BY name)


SELECT name, COUNT(*) TotalCount
FROM emp
GROUP BY name
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
--OUTPUTS

name totalcount
h     2
k     2
--it is use when name or address are null then display nonnull value
select id,coalesce(name,address) address from emp
--OUTPUTS
id  address
7    m
8    k
4    j
10    h
14    mm
--pivot value and sum of id here h and k is data of name but they became columm
SELECT  h AS h, k AS k
FROM
(SELECT id, name
FROM emp ) ps
PIVOT
(
SUM (id)
FOR name IN
( [h], [k])
) AS pvt
--OUTPUTS
columm name   h      k
data          10     8 
--display , between two value or more here all address data display with comma seprated

DECLARE @name VARCHAR(1000)

SELECT @name = COALESCE(@name,'') + address + ';'
FROM emp group by address


SELECT @name AS DepartmentNames
--OUTPUTS

DepartmentNames
a;g;l;mm;