Thursday, 25 July 2013

How to create a User control in asp.net ? & How to write methods and properties to user control in asp.net ?

Here first we have to create a user control. so, i will take a empty web application name it as "UserControl"and in this i add a user control (to add user control right click on "UserControl"  add new item 
in the left hand side click on "web" after that click on "web user control" name it as "DrpDwn.ascx"

Write the following code in .ascx page:

<table>
    <tr>
        <td>
            Select the country:
        </td>
        <td>
            <asp:DropDownList ID="Ddl_Country" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Ddl_Country_SelectedIndexChanged">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td>
            Select the State:
        </td>
        <td>
            <asp:DropDownList ID="Ddl_State" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Ddl_State_SelectedIndexChanged">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td>
            Select the City:
        </td>
        <td>
            <asp:DropDownList ID="Ddl_City" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
</table>
Here i added above 3 dropdowns first one is for to select country,
second one is for to select state and last one is for getting list of cites
which you have selcted in the state dropdown.

write the following code in .ascx.cs page:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Ddl_Country.DataSource = Country_Data();
                Ddl_Country.DataValueField = "Id";
                Ddl_Country.DataTextField = "Country_Name";
                Ddl_Country.DataBind();
                Ddl_Country.Items.Insert(0, "Select");
                Ddl_Country.Items[0].Value = "-1";
            }
        }

        public DataTable Country_Data()
        {
            DataTable dt_CountryData = new DataTable();
            dt_CountryData.Columns.Add("Id");
            dt_CountryData.Columns.Add("Country_Name");
            DataRow dr = dt_CountryData.NewRow();
            dr["Id"] = "1";
            dr["Country_Name"] = "India";
            dt_CountryData.Rows.Add(dr);
            DataRow dr1 = dt_CountryData.NewRow();
            dr1["Id"] = "2";
            dr1["Country_Name"] = "USA";
            dt_CountryData.Rows.Add(dr1);
            return dt_CountryData;

        }

        protected void Ddl_Country_SelectedIndexChanged(object sender, EventArgs e)
        {


            DataTable dt_StateData = new DataTable();
            dt_StateData.Columns.Add("Id");
            dt_StateData.Columns.Add("State_Name");
            dt_StateData.Columns.Add("Country_Id");
            DataRow dr = dt_StateData.NewRow();
            dr["Id"] = "1";
            dr["State_Name"] = "Andhrapradesh";
            dr["Country_Id"] = "1";
            dt_StateData.Rows.Add(dr);
            DataRow dr1 = dt_StateData.NewRow();
            dr1["Id"] = "2";
            dr1["State_Name"] = "Tamilnadu";
            dr1["Country_Id"] = "1";
            dt_StateData.Rows.Add(dr1);
            DataRow dr2 = dt_StateData.NewRow();
            dr2["Id"] = "3";
            dr2["State_Name"] = "California";
            dr2["Country_Id"] = "2";
            dt_StateData.Rows.Add(dr2);
            DataRow dr3 = dt_StateData.NewRow();
            dr3["Id"] = "4";
            dr3["State_Name"] = "Indiana";
            dr3["Country_Id"] = "2";
            dt_StateData.Rows.Add(dr3);

            DataView view = dt_StateData.DefaultView;
            view.RowFilter = "Country_Id =" + Ddl_Country.SelectedValue;
            view.Table.Columns.Remove("Country_Id");
            Ddl_State.DataSource = view.Table;
            Ddl_State.DataValueField = "Id";
            Ddl_State.DataTextField = "State_Name";
            Ddl_State.DataBind();
            Ddl_State.Items.Insert(0, "Select");
            Ddl_State.Items[0].Value = "-1";
            Ddl_City.ClearSelection();
            Ddl_City.Items.Clear();

        }

        protected void Ddl_State_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt_CityData = new DataTable();
            dt_CityData.Columns.Add("City_Id");
            dt_CityData.Columns.Add("City_Name");
            dt_CityData.Columns.Add("State_Id");
            DataRow dr = dt_CityData.NewRow();
            dr["City_Id"] = "1";
            dr["City_Name"] = "Visakhapatnam";
            dr["State_Id"] = "1";
            dt_CityData.Rows.Add(dr);
            DataRow dr1 = dt_CityData.NewRow();
            dr1["City_Id"] = "2";
            dr1["City_Name"] = "Hyderabad";
            dr1["State_Id"] = "1";
            dt_CityData.Rows.Add(dr1);
            DataRow dr2 = dt_CityData.NewRow();
            dr2["City_Id"] = "3";
            dr2["City_Name"] = "Vijayawada";
            dr2["State_Id"] = "1";
            dt_CityData.Rows.Add(dr2);

            DataRow dr3 = dt_CityData.NewRow();
            dr3["City_Id"] = "4";
            dr3["City_Name"] = "Coimbatore";
            dr3["State_Id"] = "2";
            dt_CityData.Rows.Add(dr3);
            DataRow dr4 = dt_CityData.NewRow();
            dr4["City_Id"] = "5";
            dr4["City_Name"] = "Madurai";
            dr4["State_Id"] = "2";
            dt_CityData.Rows.Add(dr4);
            DataRow dr5 = dt_CityData.NewRow();
            dr5["City_Id"] = "6";
            dr5["City_Name"] = "Tiruvarur";
            dr5["State_Id"] = "2";
            dt_CityData.Rows.Add(dr5);

            DataRow dr6 = dt_CityData.NewRow();
            dr6["City_Id"] = "7";
            dr6["City_Name"] = "Los Angeles";
            dr6["State_Id"] = "3";
            dt_CityData.Rows.Add(dr6);
            DataRow dr7 = dt_CityData.NewRow();
            dr7["City_Id"] = "8";
            dr7["City_Name"] = "Woodland";
            dr7["State_Id"] = "3";
            dt_CityData.Rows.Add(dr7);
            DataRow dr8 = dt_CityData.NewRow();
            dr8["City_Id"] = "9";
            dr8["City_Name"] = "San Diego";
            dr8["State_Id"] = "3";
            dt_CityData.Rows.Add(dr8);

            DataRow dr9 = dt_CityData.NewRow();
            dr9["City_Id"] = "10";
            dr9["City_Name"] = "lawrence";
            dr9["State_Id"] = "4";
            dt_CityData.Rows.Add(dr9);
            DataRow dr10 = dt_CityData.NewRow();
            dr10["City_Id"] = "11";
            dr10["City_Name"] = "south-bend";
            dr10["State_Id"] = "4";
            dt_CityData.Rows.Add(dr10);
            DataRow dr11 = dt_CityData.NewRow();
            dr11["City_Id"] = "12";
            dr11["City_Name"] = "Terre Haute";
            dr11["State_Id"] = "4";
            dt_CityData.Rows.Add(dr11);

            DataView CityView = dt_CityData.DefaultView;
            CityView.RowFilter = "State_Id =" + Ddl_State.SelectedValue;
            CityView.Table.Columns.Remove("State_Id");
            Ddl_City.DataSource = CityView;
            Ddl_City.DataValueField = "City_Id";
            Ddl_City.DataTextField = "City_Name";
            Ddl_City.DataBind();

        }

        public ArrayList SelectedText
        {
            get
            {
                ArrayList SelectedText = new ArrayList();
                if (Ddl_Country.SelectedIndex != -1 && Ddl_Country.SelectedIndex != 0)
                    SelectedText.Add(Ddl_Country.SelectedItem.ToString());
                else
                    SelectedText.Add(null);
                if (Ddl_State.SelectedIndex != -1 && Ddl_State.SelectedIndex != 0)
                    SelectedText.Add(Ddl_State.SelectedItem.ToString());
                else
                    SelectedText.Add(null);
                if (Ddl_City.SelectedIndex != -1)
                    SelectedText.Add(Ddl_City.SelectedItem.ToString());
                else
                    SelectedText.Add(null);
                return SelectedText;
            }
        }

        public ArrayList SelectedText
        {
            get
            {
                ArrayList selectedValues = new ArrayList();
                if (Ddl_Country.SelectedIndex != -1 && Ddl_Country.SelectedIndex != 0)
                    selectedValues.Add(Ddl_Country.SelectedValue.ToString());
                else
                    selectedValues.Add(null);
                if (Ddl_State.SelectedIndex != -1 && Ddl_State.SelectedIndex != 0)
                    selectedValues.Add(Ddl_State.SelectedValue.ToString());
                else
                    selectedValues.Add(null);
                if (Ddl_City.SelectedIndex != -1 )
                    selectedValues.Add(Ddl_City.SelectedValue.ToString());
                else
                    selectedValues.Add(null);

                return selectedValues;
            }
        }

 Here i created 2 properties for the user control like SelectedText, SelectedText. As per my requirement i added above.

Now take a new aspx page and name it as "page1.aspx"

write the code in aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="page1.aspx.cs" Inherits="UserControl_DrpDwn.page1" %>

<%@ Register TagPrefix="uc" TagName="Dropdown" Src="~/DrpDwn.ascx" %>
<!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">
    <script type="text/javascript">
      
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc:Dropdown ID="uc1" runat="server" />
    </div>
    <div>
        <asp:Button ID="btnNames" Text="Click" runat="server"
            OnClick="btnNames_Click" /></div>
    <div>
        <asp:Label ID="lbltext" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


 now go to code behind:

 protected void btnNames_Click(object sender, EventArgs e)
        {
            ArrayList Name = uc1.SelectedText;
            String strNames = null;
            foreach (var item in Name)
            {
                strNames += item + ",";
            }
            strNames = strNames.TrimEnd(',');
            lbltext.Text = strNames;




           ArrayList Name1 = uc1.SelectedValues;
            String strNames1 = null;
            foreach (var item in Name1)
            {
                strNames1+= item + ",";
            }
            strNames1 = strNames1.TrimEnd(',');
            label.Text = strNames1;
        }

you will get the properties.you can use here. i think so you guys learnt how to create a user control in Dotnet.
Thanks for reading.

Tuesday, 16 July 2013

How to display images using Evnet hadler in Dot Net(Images are stored in Sql server as )

To display an image in front end first we have to create an Handler. After creating handler it will display the image in aspx page.

First create an event handler (Go to website >>right click >>click on Add new item>>in the middle you will get a generic handler click on add.

after creating that write the following code :

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class ImageHandler : IHttpHandler
{

    string strcon = ConfigurationManager.AppSettings["EmployeeConnectionString"].ToString();
    public void ProcessRequest(HttpContext context)
    {
        int emp_Id = Convert.ToInt32(context.Request.QueryString["emp_Id"]);
        SqlConnection connection = new SqlConnection(strcon);
        connection.Open();
        SqlCommand command = new SqlCommand("select image from EmployeeDetails where emp_Id=" + emp_Id, connection);
        SqlDataReader dr = command.ExecuteReader();
        dr.Read();
        if (dr.HasRows)
        {
            if (dr[0] != DBNull.Value)
            {
                context.Response.BinaryWrite((Byte[])dr[0]);
                connection.Close();
                context.Response.End();
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

Note:
1)emp_Id  will get from aspx page.
2)Event handler will take the remaining things like conversion .

Now write the code in aspx.cs:

 SqlConnection connection = new SqlConnection(strcon);
            SqlCommand command = new SqlCommand("SELECT * from EmployeeDetails ", connection);
            SqlDataAdapter daimages = new SqlDataAdapter(command);
            DataTable dt = new DataTable();
            daimages.Fill(dt);
            gvImages.DataSource = dt;
            gvImages.DataBind();


Tuesday, 9 July 2013

how to upload a image into database




Byte[] imgByte = null;
        if (fileup.HasFile && fileup.PostedFile != null)
        {
            HttpPostedFile File = fileup.PostedFile;
            imgByte = new Byte[File.ContentLength];
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        empdetails.image = imgByte;

Sunday, 7 July 2013

How to get multiple tables using stored procedure Dynamically

USE [DuckCreek]
GO
/****** Object:  StoredProcedure [dbo].[Usp_Getreports]    Script Date: 07/08/2013 09:21:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- EXEC Usp_Getreports '2013-06-05 00:00:00.000', '2013-07-05 00:00:00.000', 'wc_'
ALTER procedure [dbo].[Usp_Getreports]
@Startdate date=null,
@Enddate date=null,
@Lob varchar(10)=null
as
begin
    declare @Inboundquery varchar(max)
    declare @Outboundquery varchar(max)
    declare @Failedpolicesquery varchar(max)
    declare @Reporttime varchar(max)
   
        set @Inboundquery = 'select ROW_NUMBER() OVER(ORDER BY TransactionDatatime DESC) AS SNo, * from ';
        set @Inboundquery = @Inboundquery +@Lob+'session s inner join '+@Lob+'data d on s.session_Id=d.session_Id inner join '+@Lob+'policy p on d.data_Id=p.data_Id where DATEADD(D, 0, DATEDIFF(D, 0, s.TransactionDatatime)) ';
        set @Inboundquery = @Inboundquery  + ' BETWEEN ''' + convert(varchar(10),@StartDate,110) + ''' AND ''' + convert(varchar(10),@EndDate,110) + ''''
       
       
        set @Outboundquery = 'select ROW_NUMBER() OVER(ORDER BY Record_Date DESC) AS SNo, Transaction_ID,Record_Date from ';
        set @Outboundquery = @Outboundquery +@Lob+'PROC_Trans_IDs where DATEADD(D, 0, DATEDIFF(D, 0, Record_Date))';
        set @Outboundquery = @Outboundquery + ' BETWEEN ''' + convert(varchar(10),@StartDate,110) + ''' AND ''' + convert(varchar(10),@EndDate,110) + ''''
       
        set @Failedpolicesquery = 'select ROW_NUMBER() OVER(ORDER BY TransactionDatatime DESC) AS SNo,Failedpolicy_Id,Session_Id, Error, TransactionId, TransactionDatatime from ';
        set @Failedpolicesquery = @Failedpolicesquery +@Lob+'FailedPolicies where DATEADD(D, 0, DATEDIFF(D, 0, TransactionDatatime)) ';
        set @Failedpolicesquery = @Failedpolicesquery + ' BETWEEN ''' + convert(varchar(10),@StartDate,110) + ''' AND ''' + convert(varchar(10),@EndDate,110) + ''''
       
        set @Reporttime='select convert(datetime,getdate())';
        exec (@Reporttime)
        print @Inboundquery;
        exec (@Inboundquery)
        exec (@Outboundquery)
        exec (@Failedpolicesquery)
       
       
end


Sunday, 30 June 2013

how to validate date using JavaScript

    <script type="text/javascript" language="javascript">
        function Compare() {

            var StartDate = document.getElementById('<%=TxtStartDate.ClientID %>').value;
            var EndDate = document.getElementById('<%=TxtEndDate.ClientID %>').value;
            var eDate = new Date(EndDate);
            var sDate = new Date(StartDate);
            if (sDate > eDate) {
                alert("Please ensure that the End Date is greater than or equal to the Start Date.");
                document.getElementById('<%=TxtEndDate.ClientID %>').focus();
                return false;
            }
            if (StartDate == "") {
                alert('Please select the start date ');
                document.getElementById('<%=TxtStartDate.ClientID %>').focus();
                return false;

            }
            if (EndDate == "") {
                alert('Please select the end date ');
                document.getElementById('<%=TxtEndDate.ClientID %>').focus();
                return false;
            }

            return true;
        }
        function ISspeical() {
            var charcode = window.event.keyCode;
            if (charcode == 31) {
                return false;
            }
            else
                return false;

        }
        function Clear() {
            var lbl = document.getElementById('<%=TxtEndDate.ClientID %>');
            lbl.value == "";
        }
    </script>

Sql Dynamic query using "between and operator" in sql for date comarison




        string strquery = "select ROW_NUMBER() OVER(ORDER BY s.TransactionDatatime DESC) AS SNo, s.session_Id,p.PolicyNumber,s.TransactionId,s.TransactionDatatime from ";
        strquery += strLOB;
        strquery += "session s inner join ";
        strquery += strLOB;
        strquery += "data d on s.session_Id=d.session_Id inner join ";
        strquery += strLOB;
        strquery += "policy p on d.data_Id=p.data_Id where DATEADD(D, 0, DATEDIFF(D, 0, s.TransactionDatatime)) between ";
        strquery += " " + "'" + strSdate + "'" + " and " + "'" + strEdate + "'";

Thursday, 6 June 2013

all asp.net controls in grid

htmlcode:
----------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sample1.aspx.cs" Inherits="sample1" %>

<!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">
    <script type="text/javascript" language="jscript">
        function validation() {
            employeename = document.getElementById('<%=((TextBox)gridsample.FooterRow.FindControl("txtemployeename")).ClientID%>');
            if (employeename.value == "") {
                alert("please insert Employeename..");
                employeename.focus();
                return false;
            }
            employeecode = document.getElementById('<%=((TextBox)gridsample.FooterRow.FindControl("txtemployeecode")).ClientID%>');
            if (employeecode.value == "") {
                alert("please insert employeecode..");
                employeecode.focus();
                return false;
            }
            employeesalary = document.getElementById('<%=((TextBox)gridsample.FooterRow.FindControl("txtemployeesalary")).ClientID%>');
            if (employeesalary.value == "") {
                alert("please insert Employeesalary..");
                employeesalary.focus();
                return false;
            }
            gender = document.getElementById('<%=((RadioButtonList)gridsample.FooterRow.FindControl("gender")).ClientID%>');
            if (gender.checked == false) {
                var answer = confirm("Please confirm selection...")
                if (answer)
                    return true;
                else
                    return false;
            }
            department = document.getElementById('<%=((DropDownList)gridsample.FooterRow.FindControl("department")).ClientID%>');
            if (department.value == "" || department.value == "---Select---") {
                alert("please insert department..");
                department.focus();
                return false;
            }
            skills = document.getElementById('<%=((CheckBoxList)gridsample.FooterRow.FindControl("skills")).ClientID%>');
            if (skills.value == "" || skills.value == "---Select---") {
                alert("please insert skills..");
                skills.focus();
                return false;
            }
         
            project = document.getElementById('<%=((DropDownList)gridsample.FooterRow.FindControl("projects")).ClientID%>');
            if (project.value == "" || project.value == "---Select---") {
                alert("please insert project..");
                project.focus();
                return false;
            }


        }
        function Isnumeric() {
            var charcode = window.event.keyCode;
            if (charcode > 31 && (charcode < 48 || charcode > 58)) {
                return false;
            }
            else
                return true;

        }
        function val(txtemployeename) {
            txtBxObj = document.getElementById(txtemployeename);
            if (txtBxObj.value == "") {
                alert("pppppp");
                return false;
            }
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gridsample" runat="server" AutoGenerateColumns="False" EmptyDataText="norecordsfound"
            ShowHeaderWhenEmpty="true" ShowFooter="true" ShowHeader="true" Style="margin-right: 9px"
            Width="1000px" OnRowCommand="gridsample_RowCommand" OnRowDataBound="gridsample_RowDataBound"
            DataKeyNames="employeeno" OnRowCancelingEdit="gridsample_RowCancelingEdit" OnRowDeleting="gridsample_RowDeleting"
            OnRowEditing="gridsample_RowEditing" OnRowUpdating="gridsample_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="EMPLOYEE no.">
                    <ItemTemplate>
                        <asp:Label ID="lblemployeeno" runat="server" Text='<%# Eval("employeeno") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="EMPLOYEE NAME">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtemployeename" runat="server" Text='<%# Eval ("employeename") %>'
                            Width="100px">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblemployeename" runat="server" Text='<%# Eval ("employeename") %>'
                            Width="100px"></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtemployeename" runat="server"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="EMPLOYEE Code">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtemployeecode" runat="server" Text='<%# Eval ("employeecode") %>'
                            Width="100px">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblemployeecode" runat="server" Text='<%# Eval ("employeecode") %>'
                            Width="100px"></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtemployeecode" runat="server" Text='<%# Eval ("employeecode") %>'
                            Width="100px"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="EMPLOYEE Salary">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtemployeesalary" runat="server" Text='<%# Eval ("salary") %>' onkeydown="return Isnumeric();"
                            Width="100px">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblemployeesalary" runat="server" Text='<%# Eval ("salary") %>' Width="100px"></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtemployeesalary" runat="server" Text='<%# Eval ("salary") %>' onkeydown="return Isnumeric();"
                            Width="100px">
                        </asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Gender">
                    <EditItemTemplate>
                        <asp:RadioButtonList ID="gender" runat="server">
                            <asp:ListItem Value="Male" Text="Male"></asp:ListItem>
                            <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
                        </asp:RadioButtonList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblgender" runat="server" Text='<%# Eval("gender") %>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:RadioButtonList ID="gender" runat="server">
                            <asp:ListItem Value="Male" Text="Male" Selected="True"></asp:ListItem>
                            <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
                        </asp:RadioButtonList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department">
                    <EditItemTemplate>
                        <asp:DropDownList ID="department" runat="server" Width="100px">
                            <asp:ListItem Text="---Select---"></asp:ListItem>
                            <asp:ListItem Value="dotnet" Text="dotnet"></asp:ListItem>
                            <asp:ListItem Value="java" Text="java"></asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbldepartment" Text='<%# Eval("department") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="department" runat="server" Width="100px">
                            <asp:ListItem Text="---Select---"></asp:ListItem>
                            <asp:ListItem Value="dotnet" Text="dotnet"></asp:ListItem>
                            <asp:ListItem Value="java" Text="java"></asp:ListItem>
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Skills">
                    <ItemTemplate>
                        <asp:Label ID="lblskills" Text='<%# Eval("skills") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:CheckBoxList ID="skills" runat="server">
                            <asp:ListItem Value="asp.net" Text="Asp.Net"></asp:ListItem>
                            <asp:ListItem Value="c#.net" Text="C#.Net"></asp:ListItem>
                            <asp:ListItem Value="vb.net" Text="Vb.net"></asp:ListItem>
                            <asp:ListItem Value="oracle" Text="Oracle"></asp:ListItem>
                            <asp:ListItem Value="sqlserver" Text="SQLServer"></asp:ListItem>
                            <asp:ListItem Value="java" Text="Java"></asp:ListItem>
                        </asp:CheckBoxList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:CheckBoxList ID="skills" runat="server">
                            <asp:ListItem Value="asp.net" Text="Asp.Net"></asp:ListItem>
                            <asp:ListItem Value="c#.net" Text="C#.Net"></asp:ListItem>
                            <asp:ListItem Value="vb.net" Text="Vb.net"></asp:ListItem>
                            <asp:ListItem Value="oracle" Text="Oracle"></asp:ListItem>
                            <asp:ListItem Value="sqlserver" Text="SQLServer"></asp:ListItem>
                            <asp:ListItem Value="java" Text="Java"></asp:ListItem>
                        </asp:CheckBoxList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Projects">
                    <ItemTemplate>
                        <asp:Label ID="lblproject" Text='<%# Eval("projects") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="projects" runat="server" Width="100px">
                            <asp:ListItem Text="---Select---"></asp:ListItem>
                            <asp:ListItem Value="cambridge" Text="Cambridge"></asp:ListItem>
                            <asp:ListItem Value="SVBC" Text="SVBC"></asp:ListItem>
                            <asp:ListItem Value="HRMS" Text="HRMS"></asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="projects" runat="server" Width="100px">
                            <asp:ListItem Text="---Select---"></asp:ListItem>
                            <asp:ListItem Value="cambridge" Text="Cambridge"></asp:ListItem>
                            <asp:ListItem Value="SVBC" Text="SVBC"></asp:ListItem>
                            <asp:ListItem Value="HRMS" Text="HRMS"></asp:ListItem>
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:LinkButton ID="linkupdate" runat="server" CausesValidation="true" CommandName="update"
                            Text="Update"></asp:LinkButton>
                        <asp:LinkButton ID="linkcancel" runat="server" CausesValidation="false" CommandName="cancel"
                            Text="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="linkedit" runat="server" CausesValidation="true" CommandName="edit"
                            Text="Edit"></asp:LinkButton>
                        <asp:LinkButton ID="linkdelete" runat="server" CausesValidation="false" CommandName="delete"
                            OnClientClick="return confirm('Are you certain you want to delete this employee?');"
                            Text="Delete"></asp:LinkButton>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="linkadd" runat="server" CommandName="newadd" Height="50px" Text="Add"
                            OnClientClick=" return validation()"></asp:LinkButton>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    <div>
        <asp:Label ID="lblresult" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
------------------------------------------------------------------------------------------------------------
code-back :
------------

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

namespace demo1
{
    public partial class GridSample : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=WS-ECOM12\\SQLEXPRESS;Initial Catalog=samp;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                binddata();
            }
        }
        protected void binddata()
        {
            
            SqlCommand cmd = new SqlCommand("Select * from newsamp", con);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                gridsample.DataSource = ds;
                gridsample.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gridsample.DataSource = ds;
                gridsample.DataBind();
                int columncount = gridsample.Rows[0].Cells.Count;
                gridsample.Rows[0].Cells.Clear();
                gridsample.Rows[0].Cells.Add(new TableCell());
                gridsample.Rows[0].Cells[0].ColumnSpan = columncount;
                //gridsample.Rows[0].Cells[0].Text = "No Records Found";  
            }
        }

        protected void gridsample_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("newadd"))
            {

                TextBox txtemployeename = (TextBox)gridsample.FooterRow.FindControl("txtemployeename");
                TextBox txtemployeecode = (TextBox)gridsample.FooterRow.FindControl("txtemployeecode");
                TextBox txtemployeesalary = (TextBox)gridsample.FooterRow.FindControl("txtemployeesalary");
                RadioButtonList gender = (RadioButtonList)gridsample.FooterRow.FindControl("gender");
                DropDownList department = (DropDownList)gridsample.FooterRow.FindControl("department");
                CheckBoxList skills = (CheckBoxList)gridsample.FooterRow.FindControl("skills");
                ListBox projects = (ListBox)gridsample.FooterRow.FindControl("projects");
                
                var values = "";
                for (int i = 0; i < skills.Items.Count; i++)
                {
                    if (skills.Items[i].Selected)
                    {
                        values += skills.Items[i].Value + ",";
                    }
                }
                values = values.TrimEnd(',');


                SqlCommand cmd = new SqlCommand("insert into newsamp(employeename,employeecode,salary,gender,department,skills,projects) values('" + txtemployeename.Text + "','" + txtemployeecode.Text + "','" + txtemployeesalary.Text + "','" + gender.SelectedValue + "','" + department.SelectedValue + "','" + values + "','" + projects.SelectedValue + "')", con);
                con.Open();
                int result = cmd.ExecuteNonQuery(); 
                con.Close();
                if (result == 1)
                {

                    binddata();
                    string argScript = "alert('employee added successfully');";
                    ClientScript.RegisterStartupScript(typeof(Page), "PopUp", argScript, true);
                }
                else
                {
                    string argScript = "alert('employee added unsuccessfully');";
                    ClientScript.RegisterStartupScript(typeof(Page), "PopUp", argScript, true);
                }
            }

        }
        protected void gridsample_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtemployeename = (TextBox)e.Row.FindControl("txtemployeename");
                TextBox txtemployeecode = (TextBox)e.Row.FindControl("txtemployeecode");
                TextBox txtemployeesalary = (TextBox)e.Row.FindControl("txtemployeesalary");
                RadioButtonList gender = (RadioButtonList)e.Row.FindControl("gender");
                DropDownList department = (DropDownList)e.Row.FindControl("department");
                CheckBoxList skills1 = (CheckBoxList)e.Row.FindControl("skills");
                ListBox projects = (ListBox)e.Row.FindControl("projects");
                if (gender != null)
                {
                    gender.SelectedValue = DataBinder.Eval(e.Row.DataItem, "gender").ToString();
                }
                if (department != null)
                {
                    department.SelectedValue = DataBinder.Eval(e.Row.DataItem, "department").ToString();
                }
                if (projects != null)
                {
                    projects.SelectedValue = DataBinder.Eval(e.Row.DataItem, "projects").ToString();
                }
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                string skills = row.Field<String>("skills");
                if (skills1 != null)
                {
                    string[] strskill = skills.Split(',');
                    foreach (ListItem li in skills1.Items)
                    {
                        if (strskill.Contains(li.Value))
                            li.Selected = true;
                        else
                            li.Selected = false;
                    }
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                LinkButton add = (LinkButton)e.Row.FindControl("linkadd");
                add.Attributes.Add("onclick", "adding();");
            }
        }
        protected void gridsample_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int employeeno = Convert.ToInt32(gridsample.DataKeys[e.RowIndex].Value.ToString());
            TextBox txtemployeename = (TextBox)gridsample.Rows[e.RowIndex].FindControl("txtemployeename");
            TextBox txtemployeecode = (TextBox)gridsample.Rows[e.RowIndex].FindControl("txtemployeecode");
            TextBox txtemployeesalary = (TextBox)gridsample.Rows[e.RowIndex].FindControl("txtemployeesalary");
            RadioButtonList gender = (RadioButtonList)gridsample.Rows[e.RowIndex].FindControl("gender");
            DropDownList department = (DropDownList)gridsample.Rows[e.RowIndex].FindControl("department");
            CheckBoxList skills = (CheckBoxList)gridsample.Rows[e.RowIndex].FindControl("skills");
            ListBox projects = (ListBox)gridsample.Rows[e.RowIndex].FindControl("projects");
            con.Open();
            var values = "";
            for (int i = 0; i < skills.Items.Count; i++)
            {
                if (skills.Items[i].Selected)
                {
                    values += skills.Items[i].Value + ",";
                }
            }
            values = values.TrimEnd(',');
            SqlCommand cmd = new SqlCommand("update newsamp set employeename='" + txtemployeename.Text + "', employeecode='" + txtemployeecode.Text + "',salary='" + txtemployeesalary.Text + "',gender='" + gender.SelectedValue + "',department='" + department.SelectedValue + "',skills='" + values + "',projects='" + projects.SelectedValue + "'where employeeno=" + employeeno, con);
            cmd.ExecuteNonQuery();
            con.Close();
            gridsample.EditIndex = -1;
            binddata();
            string argScript = "alert('employee update successfully');";
            ClientScript.RegisterStartupScript(typeof(Page), "PopUp", argScript, true);
        }
        protected void gridsample_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridsample.EditIndex = e.NewEditIndex;
            binddata();
        }
        protected void gridsample_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int employeeno = Convert.ToInt32(gridsample.DataKeys[e.RowIndex].Value.ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand("delete from newsamp where employeeno=" + employeeno, con);
            cmd.ExecuteNonQuery();
            con.Close();
            gridsample.EditIndex = -1;
            binddata();
            string argScript = "alert('employee deleted successfully');";
            ClientScript.RegisterStartupScript(typeof(Page), "PopUp", argScript, true);
        }
        protected void gridsample_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridsample.EditIndex = -1;
            binddata();
        }
    }
}

check box list values

This code is to get the selected values from a check box list, multi selected drop
drown , list box. 
 
for (int i = 0; i < interestedIN.Items.Count; i++)
{
   if (interestedIN.Items[i].Selected)
   {
       values += interestedIN.Items[i].Value + ",";
   }
}

values = values.TrimEnd(',');
 
 
This code will explain how to bind the selected values to a check box list,list box.
 
 
 string[] strskill = skills.Split(',');
                    foreach (ListItem li in skills1.Items)
                    {
                        if (strskill.Contains(li.Value))
                            li.Selected = true;
                        else
                            li.Selected = false;
                    }