ASP DOT NET

Tuesday, August 21, 2018

Q. How to bind treeview with database using asp.net C#?

Step 1.Create two table named VehicleTypes and VehicleSubTypes and insert some record?

CREATE TABLE [dbo].[VehicleTypes](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
 CONSTRAINT [PK_VehicleTypes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


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

CREATE TABLE [dbo].[VehicleSubTypes](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[VehicleTypeId] [int] NULL,
 CONSTRAINT [PK_VehicleSubTypes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[VehicleSubTypes]  WITH CHECK ADD  CONSTRAINT [FK_VehicleSubTypes_VehicleSubTypes] FOREIGN KEY([VehicleTypeId])
REFERENCES [dbo].[VehicleTypes] ([ID])
GO
ALTER TABLE [dbo].[VehicleSubTypes] CHECK CONSTRAINT [FK_VehicleSubTypes_VehicleSubTypes]

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

INSERT [dbo].[VehicleTypes] ([ID], [Name]) VALUES (1, N'Cars')
INSERT [dbo].[VehicleTypes] ([ID], [Name]) VALUES (2, N'Bikes')
INSERT [dbo].[VehicleTypes] ([ID], [Name]) VALUES (3, N'Heavy Vehicle')
-----------------------------------------------------------------

INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (1, N'Alto', 1)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (2, N'WagnoR', 1)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (3, N'Scorpio', 1)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (4, N'Duster', 1)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (5, N'Avenger', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (6, N'Dicover', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (7, N'Unicorn', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (8, N'Karizma', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (9, N'Hero', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (10, N'Palatina', 2)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (11, N'Maruti Suzuki', 1)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (12, N'Truck', 3)
INSERT [dbo].[VehicleSubTypes] ([ID], [Name], [VehicleTypeId]) VALUES (13, N'Luxery Buses', 3)
SET IDENTITY_INSERT [dbo].[VehicleSubTypes] OFF
SET IDENTITY_INSERT [dbo].[VehicleTypes] ON


Step 2. Now open visual studio and create aspx page.

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
 

    <style type="text/css">
        .nodeLevel1
        {
            font:40px Arial,Sans-Serif;
        }
        .nodeLevel2
        {
            font:20px Arial,Sans-Serif;
        }
        .nodeLevel3
        {
            font:10px Arial,Sans-Serif;
        }     
       
        .treeNode
        {
            transition: all .3s;
            padding: 12px 5px;
            text-align: left;
            /*width: 100%;*/
            margin: 0;
            min-width: 250px !important;
            border: 2px solid #8e44ad;
            text-decoration:none !important;
            color:black;
            /*color:blue;
            font:14px Arial, Sans-Serif;*/
        }
     .rootNode
        {
            font-size:18px;
            /*width:100%;*/
            border-bottom:Solid 1px black;
            color:#337ab7;
        }
     .leafNode {
            border: Dotted 2px black;
            padding: 10px;
            background-color: #eeeeee;
            font-weight: bold;
        }
     .selectNode
     {
        background-color:white;
        border:Dotted 2px black;
        font-weight:bold;
        color:#fff;
     }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <h3>Vehicle Details</h3>
        <hr />
        <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15"  NodeStyle-CssClass="treeNode"
    RootNodeStyle-CssClass="rootNode" ExpandDepth="1"  Font-Size="Small" HoverNodeStyle-CssClass="nodeLevel2"
    LeafNodeStyle-CssClass="leafNode" SelectedNodeStyle-CssClass="selectNode">

            <LevelStyles>
                <asp:TreeNodeStyle CssClass="nodeLevel1" />
                <asp:TreeNodeStyle CssClass="nodeLevel2" />
                <asp:TreeNodeStyle CssClass="nodeLevel3" />
                <asp:TreeNodeStyle CssClass="AspNet-TreeView-Collapse" />
                <asp:TreeNodeStyle CssClass="AspNet-TreeView-Expand" />
            </LevelStyles>

            <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
            <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
                NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
        </asp:TreeView>
    </form>
</body>
</html>


step 3. now write c# code into code behind 

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;
public partial class TreeView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
            this.PopulateTreeView(dt, 0, null);
        }
    }
    private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
    {
        foreach (DataRow row in dtParent.Rows)
        {
            TreeNode child = new TreeNode
            {
                Text = row["Name"].ToString(),
                Value = row["Id"].ToString()
            };
            if (parentId == 0)
            {
                TreeView1.Nodes.Add(child);
                DataTable dtChild = this.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE VehicleTypeId = " + child.Value);
                PopulateTreeView(dtChild, int.Parse(child.Value), child);
            }
            else
            {
                treeNode.ChildNodes.Add(child);
            }
        }
    }
    private DataTable GetData(string query)
    {
        DataTable dt = new DataTable();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }


OutPut.









Monday, August 20, 2018

Q. Update ,Insert,Delete Operation with FormView Using asp.net?

Step 1  . Create table name as Employee.

CREATE TABLE [dbo].[Employee](
[EmpID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [nvarchar](20) NOT NULL,
[FirstName] [nvarchar](10) NOT NULL,
[Address] [nvarchar](60) NULL,
[Country] [nvarchar](15) NULL,
[Designation] [nvarchar](30) NULL,
PRIMARY KEY CLUSTERED
(
[EmpID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Step 2. Insert Some record manual like below

SET IDENTITY_INSERT [dbo].[Employee] ON

INSERT [dbo].[Employee] ([EmpID], [LastName], [FirstName], [Address], [Country], [Designation]) VALUES (1, N'Firoz', N'Ansari', N'Hyderabad', N'India', N'Developer')
INSERT [dbo].[Employee] ([EmpID], [LastName], [FirstName], [Address], [Country], [Designation]) VALUES (2, N'Ansari', N'Tamanna', N'Hyderabad', N'India', N'Developer')
INSERT [dbo].[Employee] ([EmpID], [LastName], [FirstName], [Address], [Country], [Designation]) VALUES (3, N'Singh', N'MK', N'Hyderabad', N'India', N'Developer')
SET IDENTITY_INSERT [dbo].[Employee] OFF

Step 3. Write Connection String Code inside web.config

<connectionStrings>
    <add name="constr" connectionString="Data Source=INDIA;Persist Security Info=False;Integrated Security=SSPI; Initial Catalog=Northwind;User Id=sa;Password=123;
        Connect Timeout=30;"/>
 
</connectionStrings>

Step 4. Now open visual studio and create aspx page

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />+
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container py-3">
            <h2 class="text-center text-uppercase">Form View</h2>
            <div class="card">
                <asp:FormView ID="EmployeeFormView" DataKeyNames="EmpID" GridLines="Both" AllowPaging="true"
                    runat="server" OnItemDeleting="EmployeeFormView_ItemDeleting"
                    OnPageIndexChanging="EmployeeFormView_PageIndexChanging"
                    OnItemUpdating="EmployeeFormView_ItemUpdating"
                    OnItemInserted="EmployeeFormView_ItemInserted"
                    OnItemInserting="EmployeeFormView_ItemInserting"
                    OnItemUpdated="EmployeeFormView_ItemUpdated"
                    OnModeChanging="EmployeeFormView_ModeChanging" BackColor="#FFFF66"
                    BorderColor="#FF8080" EmptyDataText="Data not available">
                    <HeaderStyle BackColor="Navy" ForeColor="#999966" />
                    <RowStyle BackColor="White" ForeColor="#CC3300" />
                    <EditRowStyle BackColor="#66FF99" ForeColor="#FF9966" />
                    <ItemTemplate>
                        <table>
                            <tr>
                                <td align="left"><b>Employee ID:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("EmpID") %></td>
                            </tr>
                            <tr>
                                <td align="left"><b>First Name:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("FirstName") %></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Last Name:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("LastName") %></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Address:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("Address")%></td>
                            </tr>

                            <tr>
                                <td align="left"><b>Designation:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("Country")%></td>
                            </tr>
                             <tr>
                                <td align="left"><b>Designation:-&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</b></td>
                                <td><%# Eval("Designation")%></td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:LinkButton ID="EditButton" Text="Edit" CommandName="Edit" runat="server" />
                                    &nbsp;
                        <asp:LinkButton ID="NewButton" Text="New" CommandName="New" runat="server" />
                                    &nbsp;
                        <asp:LinkButton ID="DeleteButton" Text="Delete" CommandName="Delete" runat="server" />
                                </td>
                            </tr>
                        </table>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <table>
                            <tr>
                                <td align="left"><b>Employee ID:</b></td>
                                <td>
                                    <asp:TextBox ID="txtEmployeeID2" Text='<%# Bind("EmpID") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>First Name:</b></td>
                                <td>
                                    <asp:TextBox ID="txtFirstName2" Text='<%# Bind("FirstName") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Last Name:</b></td>
                                <td>
                                    <asp:TextBox ID="txtLastName2" Text='<%# Bind("LastName") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Address:</b></td>
                                <td>
                                    <asp:TextBox ID="txtAddress2" Text='<%# Bind("Address") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Country:</b></td>
                                <td>
                                    <asp:TextBox ID="txtCountry2" Text='<%# Bind("Country") %>' runat="Server" /></td>
                            </tr>
                               <tr>
                                <td align="left"><b>Designation:</b></td>
                                <td>
                                    <asp:TextBox ID="txtDesignation2" Text='<%# Bind("Designation") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:LinkButton ID="UpdateButton" Text="Update" CommandName="Update" runat="server" />
                                    &nbsp;
                        <asp:LinkButton ID="CancelUpdateButton" Text="Cancel" CommandName="Cancel" runat="server" />
                                </td>
                            </tr>
                        </table>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <table>
                            <%--<tr>
                                <td align="right"><b>Employee ID:</b></td>
                                <td>
                                    <asp:TextBox ID="txtEmployeeID1" Text='<%# Bind("EmpID") %>' runat="Server" /></td>
                            </tr>--%>

                            <tr>
                                <td align="left"><b>First Name:</b></td>

                                <td>
                                    <asp:TextBox ID="txtFirstName1" Text='<%# Bind("FirstName") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Last Name:</b></td>

                                <td>
                                    <asp:TextBox ID="txtLastName1" Text='<%# Bind("LastName") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Address:</b></td>
                                <td>
                                    <asp:TextBox ID="txtAddress1" Text='<%# Bind("Address") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td align="left"><b>Country:</b></td>
                                <td>
                                    <asp:TextBox ID="txtCountry1" Text='<%# Bind("Country") %>' runat="Server" /></td>
                            </tr>
                               <tr>
                                <td align="left"><b>Designation:</b></td>
                                <td>
                                    <asp:TextBox ID="txtDesignation1" Text='<%# Bind("Designation") %>' runat="Server" /></td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:LinkButton ID="InsertButton" Text="Insert" CommandName="Insert" runat="server" />
                                    &nbsp;
                        <asp:LinkButton ID="CancelInsertButton" Text="Cancel" CommandName="Cancel" runat="server" />

                                </td>

                            </tr>

                        </table>

                    </InsertItemTemplate>
                </asp:FormView>
            </div>
        </div>
    </form>
</body>
</html>


Step 5. Now goto aspx.cs file and wrire the following code.

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

public partial class FormView : System.Web.UI.Page
{
    string connStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlDataAdapter sqlda = new SqlDataAdapter();
    SqlCommand com = new SqlCommand();
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindgrid();
        }
    }
    private void bindgrid()
    {

        SqlConnection conn = new SqlConnection(connStr);
        dt = new DataTable();
        com.Connection = conn;
        com.CommandText = "SELECT * FROM Employee";
        sqlda = new SqlDataAdapter(com);
        sqlda.Fill(dt);
        EmployeeFormView.DataSource = dt;
        EmployeeFormView.DataBind();        
    }
    protected void EmployeeFormView_PageIndexChanging(object sender, FormViewPageEventArgs e)
    {
        EmployeeFormView.PageIndex = e.NewPageIndex;
        bindgrid();
    }
    protected void EmployeeFormView_ItemDeleting(object sender, FormViewDeleteEventArgs e)
    {

        //string key = EmployeeFormView.DataKey["EmpID"].ToString();


        DataKey key = EmployeeFormView.DataKey;
        if (key.Value!=null)
        {
            SqlConnection conn = new SqlConnection(connStr);
            com.Connection = conn;
            com.CommandText = "DELETE FROM Employee WHERE EmpID='" + key+ "'";
            conn.Open();
            com.ExecuteNonQuery();
            conn.Close();
            Response.Write("Record deleted successfully");
            bindgrid();
        }
        else
        {
            Response.Write("Record not deleted");
        }
    }
    protected void EmployeeFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
      
        DataKey key = EmployeeFormView.DataKey;
        if (key.Value != null)
        {
            TextBox txtFirstName = (TextBox)EmployeeFormView.FindControl("txtFirstName2");
            TextBox txtLastName = (TextBox)EmployeeFormView.FindControl("txtLastName2");
            TextBox txtAddress = (TextBox)EmployeeFormView.FindControl("txtAddress2");
            TextBox txtCountry = (TextBox)EmployeeFormView.FindControl("txtCountry2");
            TextBox txtDesignation = (TextBox)EmployeeFormView.FindControl("txtDesignation2");
            SqlConnection conn = new SqlConnection(connStr);
            com.Connection = conn;
            com.CommandText = "UPDATE Employee SET FirstName ='" + txtFirstName.Text + "',LastName ='" + txtLastName.Text + "',Address ='" + txtAddress.Text + "',Country='" + txtCountry.Text + "',Designation='" + txtDesignation.Text + "' WHERE EmpID='" + key.Value.ToString() + "'";
            conn.Open();
            com.ExecuteNonQuery();
            Response.Write("Record updated successfully");
            bindgrid();
            conn.Close();
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtAddress.Text = "";
            txtCountry.Text = "";
            txtDesignation.Text = "";
        }
        else
        {
            Response.Write("Record not Updated");
        }
    }
    protected void EmployeeFormView_ModeChanging(object sender, FormViewModeEventArgs e)
    {
        EmployeeFormView.ChangeMode(e.NewMode);
        bindgrid();
        if (e.NewMode == FormViewMode.Edit)
        {
            EmployeeFormView.AllowPaging = false;
        }
        else
        {
            EmployeeFormView.AllowPaging = true;
        }
    }
    protected void EmployeeFormView_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        EmployeeFormView.ChangeMode(FormViewMode.ReadOnly);
    }

    protected void EmployeeFormView_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
    {
        EmployeeFormView.ChangeMode(FormViewMode.ReadOnly);
    }
    protected void EmployeeFormView_ItemInserting(object sender, FormViewInsertEventArgs e)
    {        
       
        TextBox txtFirstName = (TextBox)EmployeeFormView.FindControl("txtFirstName1");
        TextBox txtLastName = (TextBox)EmployeeFormView.FindControl("txtLastName1");
        TextBox txtAddress = (TextBox)EmployeeFormView.FindControl("txtAddress1");
        TextBox txtCountry = (TextBox)EmployeeFormView.FindControl("txtCountry1");
        TextBox txtDesignation = (TextBox)EmployeeFormView.FindControl("txtDesignation1");
        SqlConnection conn = new SqlConnection(connStr);
        com.Connection = conn;
        com.CommandText = "INSERT INTO Employee(FirstName,LastName,Address,Country,Designation) Values('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + txtAddress.Text + "','" + txtCountry.Text+ "', '" + txtDesignation.Text + "')";
        conn.Open();
        com.ExecuteNonQuery();
        Response.Write("Record inserted successfully");
        bindgrid();
        conn.Close();
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtAddress.Text = "";
        txtCountry.Text = "";
        txtDesignation.Text = "";
    }   
}

Step 6.Now run the application the following page will appear.


Step 7.Whenever we will click on New link button then following page will come.
Note:- Form here you can enter some record and click on insert link button .

Step 8. Whenever click on Edit button then bellow page will apears.



Friday, August 10, 2018

Q. How to use detailsview is asp.net c# using sql server?

Step 1.Open SQL Server and create one table.

CREATE TABLE [dbo].[Customers](
[CustomerID] [nchar](5) NOT NULL,
[CompanyName] [nvarchar](40) NOT NULL,
[ContactName] [nvarchar](30) NULL,
[ContactTitle] [nvarchar](30) NULL,
[Address] [nvarchar](60) NULL,
[City] [nvarchar](15) NULL,
[Region] [nvarchar](15) NULL,
[PostalCode] [nvarchar](10) NULL,
[Country] [nvarchar](15) NULL,
[Phone] [nvarchar](24) NULL,
[Fax] [nvarchar](24) NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 2. Open visual studio and create one aspx page.

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container py-10">
            <h2 class="text-center text-uppercase">How to upload excel file in sql server database in asp.net</h2>
            <div class="card">
                <asp:DetailsView ID="DetailsView1" runat="server" DataKeyNames="CustomerID" CellPadding="6" ForeColor="#333333" AutoGenerateRows="false"
                    GridLines="None" AllowPaging="True" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateInsertButton="True" OnItemDeleting="DetailsView1_ItemDeleting"
                    OnPageIndexChanging="DetailsView1_PageIndexChanging" OnItemInserting="DetailsView1_ItemInserting" OnItemUpdating="DetailsView1_ItemUpdating"
                    OnItemInserted="DetailsView1_ItemInserted" OnItemUpdated="DetailsView1_ItemUpdated" OnModeChanging="DetailsView1_ModeChanging1">
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <Fields>
                        <asp:TemplateField HeaderText="CustomerID" Visible="True" InsertVisible="True">
                            <ItemTemplate>
                                <asp:Label ID="CustomerIDLabel" Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditCustomerID" runat="server" Text='<%# Bind("CustomerID") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertCustomerIDTextBox" runat="server" Text='<%# Bind("CustomerID") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="CompanyName">
                            <ItemTemplate>
                                <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditCompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertCompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ContactName">
                            <ItemTemplate>
                                <asp:Label ID="ContactNameLabel" runat="server" Text='<%# Bind("ContactName") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertContactNameTextBox" runat="server" Text='<%# Bind("ContactName") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="ContactTitle">
                            <ItemTemplate>
                                <asp:Label ID="ContactTitleLabel" runat="server" Text='<%# Bind("ContactTitle") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditContactTitleTextBox" runat="server" Text='<%# Bind("ContactTitle") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertContactTitleTextBox" runat="server" Text='<%# Bind("ContactTitle") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Address">
                            <ItemTemplate>
                                <asp:Label ID="AddressLabel" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditAddressTextBox" runat="server" Text='<%# Bind("Address") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertAddressTextBox" runat="server" Text='<%# Bind("Address") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="City">
                            <ItemTemplate>
                                <asp:Label ID="CityLabel" runat="server" Text='<%# Bind("City") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditCityTextBox" runat="server" Text='<%# Bind("City") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertCityTextBox" runat="server" Text='<%# Bind("City") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Region">
                            <ItemTemplate>
                                <asp:Label ID="RegionLabel" runat="server" Text='<%# Bind("Region") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditRegionTextBox" runat="server" Text='<%# Bind("Region") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertRegionTextBox" runat="server" Text='<%# Bind("Region") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="PostalCode">
                            <ItemTemplate>
                                <asp:Label ID="PostalCodeLabel" runat="server" Text='<%# Bind("PostalCode") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditPostalCodeTextBox" runat="server" Text='<%# Bind("PostalCode") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertPostalCodeTextBox" runat="server" Text='<%# Bind("PostalCode") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Country">
                            <ItemTemplate>
                                <asp:Label ID="CountryLabel" runat="server" Text='<%# Bind("Country") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditCountryTextBox" runat="server" Text='<%# Bind("Country") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertCountryTextBox" runat="server" Text='<%# Bind("Country") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Phone">
                            <ItemTemplate>
                                <asp:Label ID="PhoneLabel" runat="server" Text='<%# Bind("Phone") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditPhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertPhoneTextBox" runat="server" Text='<%# Bind("Phone") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Fax">
                            <ItemTemplate>
                                <asp:Label ID="FaxLabel" runat="server" Text='<%# Bind("Fax") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="EditFaxTextBox" runat="server" Text='<%# Bind("Fax") %>' MaxLength="10" />
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="InsertFaxTextBox" runat="server" Text='<%# Bind("Fax") %>' MaxLength="10" />
                            </InsertItemTemplate>
                        </asp:TemplateField>
                    </Fields>
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#999999" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:DetailsView>
            </div>
        </div>
        <asp:Label ID="MessageLabel" runat="server"></asp:Label>
    </form>
</body>
</html>

Step 3.Now goto code behind and write the following code which is giving bellow.

Thursday, August 9, 2018

Q. Listview Control in asp.net c# and Sql Server

Step 1. Create Table using sql server database?

CREATE TABLE [dbo].[Customers](
[CustomerID] [nchar](5) NOT NULL,
[CompanyName] [nvarchar](40) NOT NULL,
[ContactName] [nvarchar](30) NULL,
[ContactTitle] [nvarchar](30) NULL,
[Address] [nvarchar](60) NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 2. Now Insert some record?

INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'ALFKI', N'Alfreds Futterkiste', N'Maria Anders', N'Sales Representative', N'Obere Str. 57')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'ANATR', N'Ana Trujillo Emparedados y helados', N'Ana Trujillo', N'Owner', N'Avda. de la Constitución 2222')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'ANTON', N'Antonio Moreno Taquería', N'Antonio Moreno', N'Owner', N'Mataderos  2312')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'AROUT', N'Around the Horn', N'Thomas Hardy', N'Sales Representative', N'120 Hanover Sq.')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'BERGS', N'Berglunds snabbköp', N'Christina Berglund', N'Order Administrator', N'Berguvsvägen  8')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'BLAUS', N'Blauer See Delikatessen', N'Hanna Moos', N'Sales Representative', N'Forsterstr. 57')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'BLONP', N'Blondesddsl père et fils', N'Frédérique Citeaux', N'Marketing Manager', N'24')
INSERT [dbo].[Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address]) VALUES (N'BOLID', N'Bólido Comidas preparadas', N'Martín Sommer', N'Owner', N'C/ Araquil, 67')

Step 3.Now add aspx page 

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>
    <link href="Scripts/StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="container py-5">
            <h2 class="text-center text-uppercase">List View Control</h2>
            <div class="card">
                <asp:ListView ID="lvCustomers" runat="server" GroupPlaceholderID="groupPlaceHolder1"
                    ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="OnPagePropertiesChanging" HeaderStyle-CssClass="bg-primary text-white">
                    <LayoutTemplate>
                        <table class="TableCSS">
                            <tr>
                                <th>CustomerId</th>
                                <th>CompanyName</th>
                                <th>ContactName</th>
                                  <th>ContactTitle</th>
                                <th>Address</th>
                            </tr>
                            <asp:PlaceHolder runat="server" ID="groupPlaceHolder1"></asp:PlaceHolder>
                            <tr>
                                <td colspan="3">
                                    <asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvCustomers" PageSize="10">
                                        <Fields>
                                            <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
                                            <asp:NumericPagerField ButtonType="Link" />
                                            <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
                                        </Fields>
                                    </asp:DataPager>
                                </td>
                            </tr>
                        </table>
                    </LayoutTemplate>
                    <GroupTemplate>
                        <tr>
                            <asp:PlaceHolder runat="server" ID="itemPlaceHolder1"></asp:PlaceHolder>
                        </tr>
                    </GroupTemplate>
               
                    <ItemTemplate>

                        <tr class="TableData">

                            <td>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("CustomerId")%>'></asp:Label></td>
                            <td>
                                <asp:Label ID="Label3" runat="server" Text='<%# Eval("CompanyName")%>'></asp:Label></td>
                            <td>
                                <asp:Label ID="Label2" runat="server" Text='<%# Eval("ContactName")%>'></asp:Label></td>
                            <td>
                                <asp:Label ID="Label4" runat="server" Text='<%# Eval("ContactTitle")%>'></asp:Label></td>
                            <td>
                                <asp:Label ID="Label5" runat="server" Text='<%# Eval("Address")%>'></asp:Label></td>
                        </tr>

                    </ItemTemplate> 
                </asp:ListView>
            </div>
        </div>
    </form>
</body>
</html>

Step 4.Now write the below c# code into code behind

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.Configuration;
using System.Data.SqlClient;
public partial class ListView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            this.BindListView();
        }
    }
    private void BindListView()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT CustomerId, CompanyName,ContactName, ContactTitle,Address FROM Customers";
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    lvCustomers.DataSource = dt;
                    lvCustomers.DataBind();
                }
            }
        }
    }
    protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        (lvCustomers.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        this.BindListView();
    }
}

Note:- Write the following connection string into web.config

<connectionStrings>
    <add name="constr" connectionString="Data Source=HOME-PC;Persist Security Info=False;Integrated Security=SSPI; Initial Catalog=Northwind;User Id=sa;Password=dna;
        Connect Timeout=30;"/>
  
</connectionStrings>

How to to select duplicate rows from sql server?

 SELECT * FROM Recruitment WHERE Email IN (SELECT Email FROM Recruitment GROUP BY Email HAVING COUNT(*) > 1); WITH CTE AS (     SELECT   ...