Monday, June 16, 2014

Empty Rows Add in GridView

aspx Page

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
        <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Firstname">
                    <ItemTemplate>
                        <asp:TextBox ID="txtfirstname" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Lastname">
                    <ItemTemplate>
                        <asp:TextBox ID="txtlastname" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation">
                    <ItemTemplate>
                        <asp:TextBox ID="txtdesignation" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Salary">
                    <ItemTemplate>
                        <asp:TextBox ID="txtsalary" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile number">
                    <ItemTemplate>
                        <asp:TextBox ID="txtmobilenumber" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgbtn" runat="server" ImageUrl="~/Images/NARESH PIC.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="btnRegistration" runat="server" Text="Registration" OnClick="btnRegistration_Click" />
    </div>
    </form>
</body>
</html>



---------------------------------------------------------------------------------------------------
ASPC.CS

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

public partial class EmptyRowsGrid : System.Web.UI.Page
{
    Class1 obj;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session.Clear();
            GridBind();

        }

    }
    protected void btnadd_Click(object sender, EventArgs e)
    {
        if (Session["dt"] == null)
        {
            GridBind();
        }
        else
        {
            DataTable dt2 = (DataTable)Session["dt"];
            dt2.Rows.Add("", "", "", "", "");
            Session["dt"] = dt2;
            grd.DataSource = dt2;
            grd.DataBind();

        }
    }

    private void GridBind()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("firstname", typeof(String));
        dt.Columns.Add("lastname", typeof(String));
        dt.Columns.Add("designation", typeof(String));
        dt.Columns.Add("salary", typeof(String));
        dt.Columns.Add("mobilenumber", typeof(String));
        dt.Rows.Add("", "", "", "", "");
        Session["dt"] = dt;
        grd.DataSource = dt;
        grd.DataBind();
    }
    protected void btnRegistration_Click(object sender, EventArgs e)
    {
        obj = new Class1();
        foreach (GridViewRow grdobj in grd.Rows)
        {
            TextBox txt1 = (TextBox)grdobj.FindControl("txtfirstname");
            TextBox txt2 = (TextBox)grdobj.FindControl("txtlastname");
            TextBox txt3 = (TextBox)grdobj.FindControl("txtdesignation");

            TextBox txt4 = (TextBox)grdobj.FindControl("txtsalary");
            TextBox txt5 = (TextBox)grdobj.FindControl("txtmobilenumber");
            if (txt5.Text == "string")
            {
                Response.Write("values please enter numbers");

            }
            else
            {
                obj.insertvalues(txt1.Text, txt2.Text, txt3.Text, txt4.Text, txt5.Text);
            }
        }
    }

}


------------------------------------------


Inner Grid

.CS CODE

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GVOuterGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="GVOuterGrid_RowDataBound" DataKeyNames="Empid">
    <Columns>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>
    <asp:Label ID="lblDepId" runat="server" Text='<%# Bind("Empname")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Designation">
    <ItemTemplate>
    <asp:Label ID="lblDepName" runat="server" Text='<%# Bind("designation")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>



    <asp:TemplateField HeaderText="Details">
    <ItemTemplate>
    <asp:GridView ID="GVinnerGrid" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField HeaderText="Employee ID">
    <ItemTemplate>
    <asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("address")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Employee Name">
    <ItemTemplate>
    <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("gender")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>
    </ItemTemplate>
    </asp:TemplateField>

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

</html>


--------------------------
ASPX.CS

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

public partial class Grid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ado OuterGridBind = new ado();
        GVOuterGrid.DataSource = OuterGridBind.outerGrid();
        GVOuterGrid.DataBind();

    }
    protected void GVOuterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      

            ado InnerGridBind = new ado();
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //string depid="ssss";
                string DepId = GVOuterGrid.DataKeys[e.Row.RowIndex].Value.ToString();
                GridView inner = e.Row.FindControl("GVinnerGrid") as GridView;
                inner.DataSource = InnerGridBind.innerGrid(Convert.ToInt32(DepId));
                inner.DataBind();
            }
     
            Response.Write("Under Constraction");
      
    }
}


--------------------



Import Excel To Grid And Export Grid To Excel

aspx.cs socrce....

Add App_Code And App_Data oledb connectiuon...

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

<!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>
        Import Excel File:
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload"
            onclick="btnUpload_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <asp:GridView ID="gvExcelFile" runat="server" CellPadding="2" ForeColor="Black"
            GridLines="None" BackColor="LightGoldenrodYellow" BorderColor="Tan"
            BorderWidth="1px">
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
            <FooterStyle BackColor="Tan" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <SortedAscendingCellStyle BackColor="#FAFAE7" />
            <SortedAscendingHeaderStyle BackColor="#DAC09E" />
            <SortedDescendingCellStyle BackColor="#E1DB9C" />
            <SortedDescendingHeaderStyle BackColor="#C2A47B" />
        </asp:GridView>
        <br />
        <asp:Button ID="btnExport" runat="server" Text="Export to Excel" onclick="btnExport_Click1"
 />
    </div>
    </form>
</body>

</html>

.cs file...

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.OleDb;
using System.IO;
using System.Drawing;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Coneection String by default empty  
        string ConStr = "";
        //Extantion of the file upload control saving into ext because   
        //there are two types of extation .xls and .xlsx of Excel   
        string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
        //getting the path of the file   
        string path = Server.MapPath("~/MyFolder/" + FileUpload1.FileName);
        //saving the file inside the MyFolder of the server  
        FileUpload1.SaveAs(path);
        Label1.Text = FileUpload1.FileName + "\'s Data showing into the GridView";
        //checking that extantion is .xls or .xlsx  
        if (ext.Trim() == ".xls")
        {
            //connection string for that file which extantion is .xls  
            ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (ext.Trim() == ".xlsx")
        {
            //connection string for that file which extantion is .xlsx  
            ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }
        //making query  
        string query = "SELECT * FROM [Sheet1$]";
        //Providing connection  
        OleDbConnection conn = new OleDbConnection(ConStr);
        //checking that connection state is closed or not if closed the   
        //open the connection  
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        //create command object  
        OleDbCommand cmd = new OleDbCommand(query, conn);
        // create a data adapter and get the data into dataadapter  
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        //fill the Excel data to data set  
        da.Fill(ds);
        //set data source of the grid view  
        gvExcelFile.DataSource = ds.Tables[0];
        //binding the gridview  
        gvExcelFile.DataBind();
        //close the connection  
        conn.Close();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvExcelFile.AllowPaging = false;
        //BindGridview();
        //Change the Header Row back to white color
        gvExcelFile.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < gvExcelFile.HeaderRow.Cells.Count; i++)
        {
            gvExcelFile.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
        }
        gvExcelFile.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnExport_Click1(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            gvExcelFile.AllowPaging = false;
            //this.BindGrid();

            gvExcelFile.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in gvExcelFile.HeaderRow.Cells)
            {
                cell.BackColor = gvExcelFile.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in gvExcelFile.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = gvExcelFile.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = gvExcelFile.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            gvExcelFile.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
}
------------------------------------------------------------------------------------------------------------

Friday, May 9, 2014

Difference between Windows Application and Web Application?
Windows Application:
Ø Windows Applications Doesn’t Have Server tags
Ø Windows Applications Always runs on personal computers and work stations.
Ø Windows Applications extension .Exe
Ø window based app. need to be install on your machine to access
Ø windows applications (desktop) need to be installed on each client's PC.
Ø Windows application runs faster than Webapplication. 
Ø Windows application have many inbuilt classes in .Net compared to Web application.
Web Application:
Ø Web Applications Having  Server tags
Ø Web application or webapp is an application that is accessed via Web browser over a network such as the Internet or an intranet
Ø Always Run in URL
Ø Web applications are very much useful when they are hosted.Web app. can be access from anyware in the world through the internet. 
Ø Web application is tested mainly for browser compatibility and operating system compatibility, error handling, static pages, back-end testing and load testing. 
5)Web applications are programs that used to run inside some web server (e.g., IIS) to fulfill the user requests over the http. 
Ø Common Web applications include Webmail, online retail sales, online auctions, wikis, discussion boards, Weblogs
Write The Connection String in c# Language?
Web.Config file:
<connectionStrings>                                
  <add name="ASDF" providerName="System.Data.SqlClient"
       DataSource="xxx,1433;Integrated Security=True;User ID=sa;Password=123456" />
</connectionStrings>

Web.Config file to Aspx.cs page:
String XXX=System.configarationmanager.connectionstring[“asdf”].tostring();

OR
SqlConnection con=new SqlConnection(“DataSource="xxx,1433;Integrated Security=True;User ID=sa;Password=123456"”);

Write The Select Command In SqlServer?

Ø The SQL SELECT statement is used to retrieve records from one or more tables in your SQL database.

Example:
Ø Select * From Table_Name
          OR
Ø SELECT column_first,column_second
FROM table_name;
Difference between update command and alter command with examples?
Update:
Ø Used to update existing records in a Database
Ø It is a DML Command, means commands that are used to manage data without altering the DB Schema are called DML statements
Example:
Syntax:
 UPDATE  Table_name SET Col1name=value1, col2name = val2, WHERE ColXname = some value
Alter:
Ø Used to modify, delete or add a column to an existing table in a Database
Ø It is a DDL command, means  commands that are used to define the structure of a DB (DB Schema) are called DDL statements
Example:
     Syntax:
Ø ALTER  TABLE  Table_name
ADD newColname  dataTypeofNewCol  or to delete a col
DROP Colname or change datatype of an existing col in table
ALTER Column Colname newDatatype
Difference between image control and image button control in asp.net?

Image Button:
Ø ImageButton control is generally used to post the form or fire an event either client side or server side. When it is rendered on the page, generally it is implemented through <input type=image > HTML tag.

Prooerty And Descriptions:
Ø Specifies that the control is a server control.  Must be set to "server"
Ø ImageUrl: Gets or Sets the location of the image to display.
Ø PostBackUrl: Indicates the URL on which the Form will be posted back.
Ø OnClick: Attach a server side method that will fire when button will be clicked
Ø OnClientClick: Attach a client side (javascript) method that will fire when button will be clicked.
Ø  
Image:

Ø The Image control is used to display an image.
Property And Description:
Ø AlternateText: An alternate text for the image
Ø DescriptionUrl: The location to a detailed description for the image
Ø Runat: Specifies that the control is a server control.  Must be set to "server"
Ø ImageUrl: The URL of the image to display for the link
Difference between check box and radio buttons?

check box:
Ø Checkboxes may be switched independently of each other
Ø The checkbox control is used to display a check button.
Ø Check box : you can used it singly. 
Ø A checkbox is square and you can check as many as you want. 
Ø  Check box is used to indicated a boolean value: True or False 
Ø Multi-Select (Checkbox) based questions allow users to choose more than one option for the same question. This is used when the intent of the question has a "select all that apply."


radio buttons:
Ø radio buttons are part of a group where only one may be active at a time.
Ø The RadioButton control is used to display a radio button.
Ø Radio Box: if you want to make a multiple choice in your program such as in the Options dialog of you program. For example, you want user to choose between "Save work into file" or "Save work into memory", you can apply with Radio Box. 
Ø A radiobutton is round and you can just check one per group.
Ø  A groupe of Radio Buttons is used when you have more choices than True or False... say you have a choice like "Maybe".
Ø Single-Select (Radio) based questions allow users only to choose one (and only one) option for any given question. This is used when the intent of the question is "select one."
7) Explain About constraints with example?

Constraints in a database maintain the integrity of the database.

RDBMS Stands for (Relational dataBase management System)
Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.
Types of constraints:

--> PRIMARY KEY
 --> UNIQUE
 -->FOREIGN KEY
 --> CHECK
--> NOT NULL

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

A FOREIGN KEY constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.

A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

You can create constraints when the table is created, as part of the table definition by using the CREATE TABLE statement
  
Example

CREATE TABLE employee(
   EmployeeId INT NOT NULL,
   LName VARCHAR(30) NOT NULL,
   FName VARCHAR(30) NOT NULL,
   Address VARCHAR(100) NOT NULL,
   HireDate DATETIME NOT NULL,
   Salary MONEY NOT NULL CONSTRAINT check_sale CHECK (salary > 0)
)

ALTER TABLE employee
ADD CONSTRAINT pk_employee PRIMARY KEY (EmployeeId)

ALTER TABLE employee
DROP CONSTRAINT pk_employee



Types of constraints
I focus on four types of constraints: primary key, foreign key, unique, and check. Here's a brief overview of each.

Primary key
This constraint is used to guarantee that a column or set of columns on a table contain unique values for every record in the given table. This lets you ensure data integrity by always being able to uniquely identify the record in the table.

Get SQL tips in your inbox
TechRepublic's SQL Server newsletter, delivered each Tuesday, contains hands-on tips that will help you become more adept with this powerful relational database management system.
Automatically sign up today!
A table can have only one primary key constraint defined on it, and the rows in the primary key columns cannot contain null values. A primary key constraint can be defined when a table is created, or it can be added later.

This script creates a primary key constraint on a single field when the table is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
 CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL
)
 GO
The followings script creates the primary key constraint when the table is created. This method allows you to define a name for the constraint and to create the constraint on multiple columns if necessary.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
CREATE TABLE SalesHistory(
      SaleID int IDENTITY(1,1) NOT NULL,
      Product char(150) NULL,
      SaleDate datetime NULL,
      SalePrice money NULL,
      CONSTRAINT pk_SaleID PRIMARY KEY (SaleID)
 )
 GO
This script creates the primary key constraint on the table after it is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO

 CREATE TABLE SalesHistory(
      SaleID  int IDENTITY(1,1) NOT NULL,
      Product  char(150) NULL,
      SaleDate  datetime NULL,
      SalePrice  money NULL
 )
 GO
 ALTER TABLE SalesHistory
 ADD CONSTRAINT pk_SaleID PRIMARY KEY (SaleID)
 GO
Foreign key
This constraint limits the values of columns in one table based upon the values of columns in another table. This link between the two tables requires the use of a "lookup table," which contains the accepted list of values; this list must contain a unique or primary key constraint. After the constraint is established between the two tables, any data modifications to the fields defined in the constraint on the foreign key table will cause a validation to ensure that the data being updated or inserted is contained in the lookup table.

The script in Listing A creates a ProductTypes table, which will serve as the lookup table and the SalesHistory table, which will reference the ProductID in the ProductTypes table. If I had excluded the constraint definition in the table declaration, I could go back later and add it. You can do this with the script in Listing B.

The previous script contains the WITH NOCHECK clause. I use it so that any existing values in the table are not considered when the constraint is added. Any records in the table that violate the newly added constraint will be ignored so that the constraint is created. The constraint will only be applicable to new records entered into the SalesHistory table.

Unique
This constraint guarantees that the values in a column or set of columns are unique. Unique and primary key constraints are somewhat similar because each provide a guarantee for uniqueness for a column or set of columns. A primary key constraint automatically has a unique constraint defined on it.

There are two differences between the constraints: (1) You may have only one primary key constraint per table, yet you may have many unique constraints per table; (2) A primary key constraint will not allow null values but a unique constraint will (although it will only allow one null value per field).

This script creates a unique constraint on the SaleID column when the table is created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] NOT NULL UNIQUE,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL
 )
 GO
The following script creates a unique constraint on the table at creation, and it allows for constraint naming and for defining the unique constraint on multiple columns if necessary.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
 CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int]  NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL,
      CONSTRAINT uc_SaleID UNIQUE (SaleID)
 )
 GO
This script creates the unique constraint on the SalesHistory table by altering the table after it has been created:

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
 CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int] NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL
 )
 GO
 ALTER TABLE SalesHistory
 ADD CONSTRAINT uc_SaleID UNIQUE(SaleID)
 GO
Check
This constraint limits the value range, or domain, in a column. Check constraints check the acceptable values against a logical expression defined in the constraint. These constraints are similar to foreign key constraints in that they both govern the acceptable values for a column or set of columns in a given row in a table. You can create a check constraint at the column or table level. A check constraint on a single column allows only certain values for those columns, while a table check constraint can limit values in certain columns based on values in other fields in the row.

The following script creates a check constraint on the SalePrice column in the SalesHistory table, limiting entries where the SalePrice must be greater than 4. Any attempt to enter a record with the SalePrice present and less than 4 will result in an error.

IF OBJECT_ID('SalesHistory')>0
      DROP TABLE SalesHistory;
 GO
 CREATE TABLE [dbo].[SalesHistory](
      [SaleID] [int]  NOT NULL,
      [Product] [char](150) NULL,
      [SaleDate] [datetime] NULL,
      [SalePrice] [money] NULL CHECK (SalePrice > 4)
 )
 GO
 Namespaces in asp.net?

 Namespaces:
Ø Collection of Classes Is Called Namespace.
Ø Namespaces are a way of grouping type names and reducing the chance of name collisions.
Ø Namespace is logical division of class, structure and interface OR way to organize your Visual Basic .NET code is through the use of namespaces
Ø The namespace with all the built-in functionality comes under System namespace. All other namespaces comes under this System namespace.
Namespace Declaration in C#
Ø using System;
Ø using System.Data;
Namespace Declaration in Vb
Ø imports system;
Ø imports system.Data;
Example:
namespace ExampleNamespace
        {
            class TestExample
            {
                public void ShowMessage()
                {
                    Console.WriteLine("This is the TestExample namespace!");
                }
            }
        }

1) The System.Web namespace

System.web namespace holds some basic ingredients which includes classes and built-in Objects like
a.     Server
b.     Application
c.      Request
d.     Response
And Classes used for managing
a.     Cookies
b.     Configuring page caching
c.      Tracing Implementation
d.     Retrieving Information of Web Server and client browser
We uses built-in object frequently .This namespace are very important for ASP.net application, it is also required for User Interface , Web forms and Web services.

2) The System.Web.services namespace

The System.Web.services namespace is a initial point for creating the web services. It contains web service classes , which allow to create XML web services using Asp.Net . XML web services provides feature to exchange messages in loosely coupled environment. using protocol like SOAP , HTTP , XML .

Some classes are as follows
a.     WebMethodAttribute
b.     Webservice
c.      WebServiceAttribute
d.     WebServiceBindingAttribute
3) The System.web.UI.WebControls namespace

The System.web.UI.WebControls namespace contains classes that provides to create web server controls on web pages. These controls run on the server so we can programmaticaly control elements . It also include form controls like text boxes and buttons. special purpose controls such as calender , and Data Grid . Web controls are more abstract than HTML controls . They also provide a shophisticated formatting properties and events . The System.web.UI.WebControls namespace contains web control class which is the base class for all web controls

Some classes are as follows
a.     Calendar
b.     Check Box
c.      Button
d.     Base Data Bound Control
e.     Data Control Field etc
4) The System.web.UI namespace

The System.web.UI namespace includes classes that allows to create server controls with data- binding functionality , which has ability to save view state of given control and pages (.aspx pages) . Many of these types allows to support for controls System.web.UI .Html controls. It is a base class for all HTML ,Web, and User Controls. Every aspx pages comes under it. Control classes provides common set of functionslity

There are following controls available
  • HTML server controls
  • Web server controls
  • User controls
Some classes are as follows
a.     Attribute Collection
b.     BaseParser
c.      BaseTemplateParser
d.     AsyncPostBackTrigger etc
5) The System.web.sessionstate namespace

Session state management comes under The System.web.sessionstate namespace . That enable storage of data specific to a single client with in a web application on the server. Session state is ideal for sensitive data such as mailing address , credit card number , password , important numbers etc. Sesssion state can be used with clients that do not support cookies.

Some classes are as follows
a.     HttpSessionState
b.     HttpSessionStateContainer
c.      SessionIDManager
d.     SessionStateModule etc
Insert Command with Examples?
 > The INSERT INTO statement is used to insert new records in a table.
>  The SQL INSERT statement is used to insert a one or more records into a table.
Syntax:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
And
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Alter command with examples?
Alter:
Ø ALTER TABLE statement to add a column, modify a column, drop a column, rename a column or rename a table (with lots of clear, concise examples). We've also added some practice exercises that you can try for yourself.
Ø The SQL ALTER TABLE command is used to modify the definition (structure) of a table by modifying the definition of its columns. The ALTER command is used to perform the following functions.
Syntax to add a column

ALTER TABLE table_name ADD column_name datatype;
For Example: To add a column "experience" to the employee table, the query would be like
ALTER TABLE employee ADD experience number(3);
Syntax to drop a column
ALTER TABLE table_name DROP column_name;
For Example: To drop the column "location" from the employee table, the query would be like
ALTER TABLE employee DROP location;
Syntax to modify a column
ALTER TABLE table_name MODIFY column_name datatype;
For Example: To modify the column salary in the employee table, the query would be like
ALTER TABLE employee MODIFY salary number(15,2);