Saturday 9 March 2013

What is LINQ



What is Linq?
It is Language Integration Query.
If someone does not know about the syntax of SQL Server (working in SQL Environment). After understanding the syntax of LINQ they can easily work with Microsoft SQL Server .
Like: - Insert command, Select Command, Update Command and Delete Command.
In Linq we use var keyword to declare any object .
For example:-
Var obj=123;
Var objstring=”rahul Gupta” etc……
If we declare an object with var keyword then the object can store any type of Value.



Linq Without DBML File




ASPX.CS Code

.CS Code (Class file)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq.Mapping;



[Table(Name = "stu_info")]
public class Person
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int roll { get; set; }
    [Column]
    public string Name { get; set; }
    [Column]
    public string LName { get; set; }
}


ASPX CODE

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
  
    </form>
</body>
</html>




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


public partial class _Default : System.Web.UI.Page
{
    //BusinessObjects db = new BusinessObjects();
    public string constr = @"Data Source=RAMUTELECOM\RKUMAR;Initial Catalog=test3;Persist Security Info=True;User ID=sa;Password=mysachi";
    protected void Page_Load(object sender, EventArgs e)
    {

        DataContext db = new DataContext(constr);
       GridView1.DataSource = db.GetTable<Person>().ToList();
       GridView1.DataBind();
     
    
          
    }




    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(constr);
        SqlCommand com = new SqlCommand("exec sp_twotable", con);
        con.Open();
        SqlDataReader dr = com.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        dr.NextResult();
        GridView2.DataSource = dr;
        GridView2.DataBind();
        con.Close();
    }
}

Friday 8 March 2013

How to insert record into identity column in Sql Server



How to insert record into identity column in Sql Server



Step:1- Create a table

create table student(id int identity(1,1) not null primary key,name varbinary(50))

Insert Data in student table in Sql :-

 insert into student(name) values('Ramu Gupta')

When you enter record this way:-
 insert into student(id,name) values(1,'Ramu Gupta')

The above written sql program  will generate error. But we can insert data in identity column by this way….
Set identity_insert on
insert into student(id,name) values(1,'Ramu Gupta')
insert into student(id,name) values(2,'Sachi Gupta')
Set identity_insert off










Thursday 7 March 2013

How to Insert Record with Footer Row Controls



How to Insert Record with Footer Row Controls








ASPX PAGE CODE

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

<!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>Untitled Page</title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .lft20
        {
          margin-left:50px;
          position :relative ;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:GridView ID="GridView1" runat="server" ShowFooter="True"
        AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
        GridLines="None" onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting"
        onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
       >
        <RowStyle BackColor="#EFF3FB" />
    <Columns >
        <asp:CommandField ShowEditButton="True" />
        <asp:CommandField ShowDeleteButton="True" />
    <asp:TemplateField HeaderText ="Id">
   
    <ItemTemplate>
   
    <asp:Label ID="lblid" runat ="server" Text='<%# bind("id") %>'></asp:Label>
   
    </ItemTemplate>
   
    </asp:TemplateField>
   
    <asp:TemplateField HeaderText ="Name">
  
    <ItemTemplate>
   
    <asp:Label ID="lblname" runat ="server" Text='<%# bind("name") %>' CssClass ="lft20" ></asp:Label>
   
    </ItemTemplate>
    <EditItemTemplate>
   
    <asp:TextBox ID="txtname" runat ="server" Width ="120px" Height="20px" Text ='<%# bind("name") %>'></asp:TextBox>
   
    </EditItemTemplate>
   <FooterTemplate>
  
 
  
    <table class="style1">
           <tr>
               <td>
                   Name</td>
               <td>
                   <asp:TextBox ID="txtnamef" runat="server" Height="22px" Width="120px"></asp:TextBox>
                   <asp:Button ID="Button1" runat="server" CommandName="Insert" Height="24px"
                       Text="Add" Width="52px" />
               </td>
           </tr>
       </table>
     </FooterTemplate>
    </asp:TemplateField>
      </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="Pink" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    </form>
</body>
</html>

ASPX.CS PAGE CODE

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

public partial class Default2 : System.Web.UI.Page
{
    #region Public variable
       DataTable dt;
       SqlDataAdapter da;
       SqlCommandBuilder scb;
       public string constr =       ConfigurationManager.ConnectionStrings["DemoConnectionString2"].ConnectionString.ToString();
    #endregion

    /// <summary>
    /// Binding GridView in Form Load Event when page is not postback
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            fillgrid();
        }
    }
    /// <summary>
    /// Method for fill GridView in Disconnected Architecture
    /// </summary>
    public void fillgrid()
    {
        da = new SqlDataAdapter("select * from stu_info", constr);
        dt = new DataTable();
        da.Fill(dt);

        #region to show fotter row in grind view if table is empty
        if (dt.Rows.Count < 1)
        {
            dt.Rows.Add(dt.NewRow());
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.Rows[0].Style.Add("display", "none");

        }
        #endregion
        #region bind gridview with datatable
        else
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        #endregion

    }
   /// <summary>
   /// Insert Record with footer TextBox
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //TextBox t1 = ((TextBox)GridView1.FooterRow.Cells[3].Controls[1]);
      

      
            if (e.CommandName == "Insert")
            {
                TextBox t1 = ((TextBox)GridView1.FooterRow.Cells[3].FindControl("txtnamef"));
                if (t1.Text.Trim().Length > 0)
                {
                da = new SqlDataAdapter("select * from stu_info", constr);
                dt = new DataTable();
                da.Fill(dt);
                DataRow dr = dt.NewRow();
                dr["name"] = t1.Text;
                dt.Rows.Add(dr);
                scb = new SqlCommandBuilder(da);
                da.Update(dt);
                fillgrid();
                }
                else
                {
   #region Footer TextBox is empty then alert Please enter name and set focus in footer TextBox

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "<script> alert('" + " Please Enter Name" + "')" + "</script>", false);
                    t1.Focus();
                    #endregion
                }
            }
      
       
    }
    /// <summary>
    /// Deleting a particular row in GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        da = new SqlDataAdapter("select * from stu_info", constr);
        dt = new DataTable();
        da.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            #region if id match in gridview row
            if (dr[0].ToString() == ((Label)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text)
            #endregion
            {
                #region deleting Row and UpdatePanel DataTable and Bind grinview
                  
                dr.Delete();
                scb = new SqlCommandBuilder(da);
                da.Update(dt);
                fillgrid();
                      #endregion
                break;
            }
        }
    }
    /// <summary>
    /// Generate edit row index
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }
    /// <summary>
    /// Removing edit row index
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }
    /// <summary>
    /// Update the Name with gridview edit row
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        da = new SqlDataAdapter("select * from stu_info", constr);
        dt = new DataTable();
        da.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            if (dr[0].ToString() == ((Label)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text)
            {
                dr["name"] = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[1]).Text;
                scb = new SqlCommandBuilder(da);
                da.Update(dt);
                GridView1.EditIndex = -1;
                fillgrid();
                break;
            }
        }
     
    }
  
}