Wednesday, 28 December 2011

FileUpload Save Images and File in Folder

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
        <form id="form1" runat="server">
        <div>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> 
        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label><asp:HiddenField ID="HiddenField1"
        runat="server" />
    </div>
    </form>
</body>
</html>
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 _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    public void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
        if (FileUpload1.HasFile)
    {
        string filename = FileUpload1.FileName.ToString();
        
            try
        {
           
            string path = FileUpload1.PostedFile.FileName.ToString();
            FileUpload1.SaveAs(Server.MapPath("image/" + filename));
            lblMsg.Text = "Upload status: File uploaded!";
            int imgSize = FileUpload1.PostedFile.ContentLength;
        }
        catch(Exception ex)
        {
            lblMsg.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }

    }
   
}

Monday, 26 December 2011

Database for GridView

Create Database emp and Then Execute the tables
USE [emp]
GO
/****** Object:  Table [dbo].[empdetails]    Script Date: 12/27/2011 10:30:14 ******/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[empdetails](
    [empno] [int] IDENTITY(1,1) NOT NULL,
    [empname] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [empcode] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [department] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [salary] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [gender] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [skill] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [project] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF



USE [emp]
GO
/****** Object:  Table [dbo].[department]    Script Date: 12/27/2011 10:29:15 ******/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[department](
    [department] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF


USE [emp]
GO
/****** Object:  Table [dbo].[projects]    Script Date: 12/27/2011 10:30:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[projects](
    [projectname] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
       

Sunday, 11 December 2011

Gridview with add edit and delete with validation in javscript and required field validations

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<font color="#000000"><style type="text/css">
body
{

}
#status
{
font-size:11px;
margin:10px;
}
.availablecss
{
background-color:#CEFFCE;

}
.notavailablecss
{
background-color:#FFD9D9;

}

</style>
</font>  
<title>grid add & edit</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript"  language="javascript">

////////////////////////////////////check field validation/////////////////////////////////////////////////

function ValidateGrid()
{
txtempName = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempName")).ClientID%>');
txtempcode = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempcode")).ClientID %>');
DropDownList2 = document.getElementById('<%=((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).ClientID%>');
txtsalary = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtsalary")).ClientID %>');
//listItemArray = document.getElementById('<%=((RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2")).ClientID %>');

if(txtempName.value == 0)
{
alert("Please enter name...!");
txtempName.focus();
return false;
}
if(txtempcode.value == 0)
{
alert("Please Enter Emp code...!");
txtempcode.focus();
return false;
}
var str='';

var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
var SearchText = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempcode")).ClientID %>').value;
var lenth =Grid_Table.rows.length;
if(lenth > 3)
{
for(var row=1; row<Grid_Table.rows.length-1; row++)
{
for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
{
if(col==0)
 if(document.all[col])
  str=str+Grid_Table.rows[row].cells[2].innerText;
}
} 
}          str=str+'\n'; 
   var array=str.split(" "); 
   for(i = 0; i < array.length; i ++)

{ 

if(array[i] == SearchText)
{
//break;
alert("empcode  already exist");
return false;
}
}
if(DropDownList2.value == 0)
{
alert("Please select ...!");
DropDownList2.focus();
return false;
}
if(txtsalary.value == 0)
{
alert("Please Enter salary...!");
txtsalary.focus();
return false;
}
var numericExpression = /^[0-9]+$/;
if(txtsalary.value.match(numericExpression)){
return true;
}else{
alert("enter Number only");
txtsalary.focus();
return false;
}
var BaseControl = null;
BaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
if (BaseControl == null)
return false;           
var ChildControl = "CheckBoxList1";
var Inputs = BaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
 if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(ChildControl, 0) >= 0 && Inputs[n].checked)
  var valid= true;
if(!valid)
{
alert('Select at least one Skill..!');
 return false;
 
}

var grid = document.getElementById('<%= GridView1.ClientID %>');
var rlength=grid.rows.length;
var clength=rlength-1;
var proj=grid.rows[clength].cells[7].childNodes[0];
for(i = 0; i < proj.length; i++) 
{
if(proj[i].selected)
{
var isvalid=true;
break;
}
    }
if(!isvalid){
alert("select atleast one project..! "); 
return false;
}
return true;
} 

///////////////////////////////////////////delete confirmation//////////////////////////////

function ConfirmationBox(empno) {
var result = confirm('Are you sure you want to delete '+empno+' employee id Details' );
if (result) {
return true;
}
else {
return false;
}
}
////////////////////////////////////checkskill/////////////////////////////////////
function Checkskill(sender, args)
{
BaseContrl = document.getElementById('<%= this.GridView1.ClientID %>');
var ChildContro = "CheckBoxList2";
var Inputs1 = BaseContrl.getElementsByTagName("input");
var ischecked=false;
args.IsValid =false;
for(i=0;i<Inputs1.length;i++)
{
var opt = Inputs1[i];
if(opt.type=="checkbox" && opt.id.indexOf(ChildContro, 0) >= 0 && opt.checked)
{
if(opt.checked)
{
    ischecked= true;
    args.IsValid = true;                
}
}
}

}

//////////////////////////////checkproject/////////////////////////////////   

function projectselect(sender, args)
{
debugger;
BaseContrl1 = document.getElementById('GridView1');
var ChildContro1 = "ListBox1";
var Inputs2 = BaseContrl1.getElementsByTagName("input");
var ischecked1=false;
args.IsValid1=false;

for(i=0;i<Inputs2.length;i++)
{
var opt = Inputs2[i];
if(opt.type=="ListBox" && opt.id.indexOf(ChildContro1, 0) >= 0 && opt.selected)
{
if(opt.selected)
{
    ischecked= true;
    args.IsValid = true;                
}
}
}

}


/////////////////////////////////checkduplicate value/////////////////////////    
</script>

<script type="text/javascript" language="javascript">

$(document).ready(function() {

var sname= $("#GridView1 input[name*='TextBox2']");

$(sname).change(function() {
var uname = $("#GridView1 input[name*='TextBox2']");
var msgbox = $("#GridView1 span[id*='status']");
if (uname.val().length >= 4) {
$.ajax({
type: "POST",
url: "Register.aspx/CheckUserName",
data: "{'args': '" + uname.val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
uname.removeClass("notavailablecss");
uname.addClass("availablecss");
msgbox.html(' <font color="Green"> Available </font>');
    }
else {
uname.removeClass("availablecss");
uname.addClass("notavailablecss");
msgbox.html(msg.d);
        }
    }
});
}
else {
uname.addClass("notavailablecss");
msgbox.html('<font color="#cc0000">Ecode must be 4 characters</font>');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
CellPadding="4" ForeColor="#333333" GridLines="None"  ShowFooter="true"
onrowcancelingedit="GridView1_RowCancelingEdit" 
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
onrowdatabound="GridView1_RowDataBound"  OnRowDeleting="GridView1_RowDeleting"   ShowHeader="True">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate >
<asp:Label ID="Label6" runat="server" Text='<%# Eval("empno") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate >
<asp:Label runat="server" Text='<%# Eval("empname") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("empname")%>'  ></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Requiredempname" ControlToValidate="TextBox1" ValidationGroup="editmode"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtempName" Width="70px" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Code">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("empcode") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("empcode") %>' ></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Requiredempcode" ControlToValidate="TextBox2" ValidationGroup="editmode"></asp:RequiredFieldValidator>
<br />
<span id="status"></span>
</EditItemTemplate>
<FooterTemplate> 
<asp:TextBox ID="txtempcode" Width="70px" runat="server"  />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate >
<asp:Label ID="Label2" runat="server" Text='<%# Eval("department") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:DropDownList ID="DropDownList1" runat="server"  >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Requireddepartment" ControlToValidate="DropDownList1" ValidationGroup="editmode">
</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSource= '<%# PopulateControls() %>' DataTextField="department" DataValueField="department"  >
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<ItemTemplate >
<asp:Label ID="Label3" runat="server" Text='<%# Eval("salary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("salary") %>' ></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Requiredsalary" ControlToValidate="TextBox3"  ValidationGroup="editmode"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtsalary" Width="70px" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<ItemTemplate >
<asp:Label ID="Label4" runat="server" Text='<%# Eval("gender") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:RadioButtonList ID="RadioButtonList1" runat="server" >
<asp:ListItem >Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="RadioButtonList2" runat="server">
<asp:ListItem Selected="True">Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="skill">
<ItemTemplate >
<asp:Label ID="Label5" runat="server" Text='<%# Eval("skill") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:CheckBoxList ID="CheckBoxList2" runat="server" >
<asp:ListItem>asp.net</asp:ListItem>
<asp:ListItem>c#</asp:ListItem>
<asp:ListItem>java</asp:ListItem>
<asp:ListItem>php</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator  ClientValidationFunction="Checkskill"  ID="ValidateAge" runat="server" ErrorMessage="Please Select skill" ValidationGroup="editmode" > </asp:CustomValidator>  
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"   >
<asp:ListItem>asp.net</asp:ListItem>
<asp:ListItem>c#</asp:ListItem>
<asp:ListItem>java</asp:ListItem>
<asp:ListItem>php</asp:ListItem>
</asp:CheckBoxList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>  
<asp:ListBox ID="ListBox1" runat="server" DataSource= '<%# PopulateControlslist() %>' DataTextField="projectname" DataValueField="projectname" SelectionMode="Multiple">
</asp:ListBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5"  ControlToValidate="ListBox1" runat="server" ErrorMessage="select one project" ValidationGroup="editmode"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:ListBox ID="ListBox2" runat="server" DataSource= '<%# PopulateControlslist() %>' DataTextField="projectname" DataValueField="projectname"  SelectionMode="Multiple">
</asp:ListBox>
</FooterTemplate>  
<ItemTemplate>  
<asp:Label ID="lblState" runat="server" Text='<%#Eval("project")%>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"  ></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update"  ValidationGroup="editmode" ></asp:LinkButton>
<asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="delete" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btndelete" runat="server" CommandName="Delete" Text="Delete"  ></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnSave" runat="server" Text="Save"  OnClick="save" OnClientClick="return ValidateGrid();"  />
</FooterTemplate>  
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</form>
</body>
</html>

C# code Behind

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;


public partial class _Default : System.Web.UI.Page
{
public string sVendors = "";
public string sSkill = "";
string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection sqlcon;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        showgrid();
    }
}
public void showgrid()
{
    DataTable dt = new DataTable();
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    SqlDataAdapter sda = new SqlDataAdapter();
    string strQuery = "select * from empdetails ";
    SqlCommand cmd = new SqlCommand(strQuery);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    if (dt.Rows.Count > 0) //Check if DataTable returns data

        {
        GridView1.DataSource = dt;
        GridView1.DataBind();
        }
    else       
        {   
                ShowNoResultFound(dt,GridView1);
            }
    }
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    showgrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    showgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
    DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1");
    RadioButtonList rbl = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
    CheckBoxList chb = (CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList2");
    TextBox tx1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
    TextBox tx2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
    TextBox tx3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
    ListBox llb = (ListBox)GridView1.Rows[e.RowIndex].FindControl("ListBox1");
    string ski = "";
    foreach (ListItem selectedItem in chb.Items)
    {
        if (selectedItem.Selected)
        {
            if (ski.Length == 0)
                ski = selectedItem.Value;
            else
                ski = ski + "," + selectedItem.Value;
        }
    }

    string pro = "";
    foreach (ListItem selectedItem in llb.Items)
    {
        if (selectedItem.Selected)
        {
            if (pro.Length == 0)
                pro = selectedItem.Value;
            else
                pro = pro + "," + selectedItem.Value;

        }
    }
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "update empdetails set empname='" + tx1.Text + "',empcode='" + tx2.Text + "',department='" + ddl.SelectedValue.ToString() + "',salary='" +
    tx3.Text + "',gender='" +
    rbl.SelectedValue.ToString() + "',skill='" + ski + "',project='" + pro + "' where empno='" + lb.Text + "'";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    cmd.ExecuteNonQuery();
    GridView1.EditIndex = -1;
    showgrid();
}
public DataTable load_department()
{
    DataTable dt = new DataTable();
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "select * from department";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    SqlDataAdapter sd = new SqlDataAdapter(cmd);
    sd.Fill(dt);
    return dt;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DataRowView drv = e.Row.DataItem as DataRowView;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DropDownList dp = (DropDownList)e.Row.FindControl("DropDownList1");

            DataTable dt = load_department();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ListItem lt = new ListItem();
                lt.Text = dt.Rows[i][0].ToString();
                dp.Items.Add(lt);
            }
            dp.SelectedValue = drv[3].ToString();
            RadioButtonList rbtnl = (RadioButtonList)e.Row.FindControl("RadioButtonList1");
            rbtnl.SelectedValue = drv[5].ToString();
            CheckBoxList chkb = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
            string[] strSplitArr = ((DataRowView)e.Row.DataItem)["skill"].ToString().Split(',');
            foreach (ListItem oItem in chkb.Items)
            {
                for (int i = 0; i < strSplitArr.Length; i++)
                {
                    if (oItem.Value == strSplitArr[i].Trim())
                    {
                        oItem.Selected = true;
                        break;
                    }
                }
            }
            ListBox llb = (ListBox)e.Row.FindControl("ListBox1");
            string[] strSplit = ((DataRowView)e.Row.DataItem)["project"].ToString().Split(',');
            foreach (ListItem oItem in llb.Items)
            {
                for (int i = 0; i < strSplit.Length; i++)
                {
                    if (oItem.Value == strSplit[i].Trim())
                    {
                        oItem.Selected = true;
                        break;
                    }
                }
            }
        }

        string empno = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "empno"));
        LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("btndelete");
        lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + empno + "')");
    }
}
protected void save(object sender, EventArgs e)
{


    Control control = null;

    if (GridView1.FooterRow != null)
    {
        control = GridView1.FooterRow;
    }
    else
    {
        control = GridView1.Controls[0].Controls[0];
    }
    string empname = (control.FindControl("txtempName") as TextBox).Text;
    string empcode = (control.FindControl("txtempcode") as TextBox).Text;
    string department = (control.FindControl("DropDownList2") as DropDownList).Text;
    string salary = (control.FindControl("txtsalary") as TextBox).Text;
    string gender = (control.FindControl("RadioButtonList2") as RadioButtonList).Text;
    //string skill = (control.FindControl("CheckBoxList1") as CheckBoxList).Text;
    //string project = (control.FindControl("ListBox2") as ListBox);
    string strConnString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    StringCollection sc = new StringCollection();
    ListBox project = GridView1.FooterRow.FindControl("ListBox2") as ListBox;
    CheckBoxList skill = GridView1.FooterRow.FindControl("CheckBoxList1") as CheckBoxList;
    foreach (ListItem selectedItem in project.Items)
    {
        if (selectedItem.Selected)
        {
            if (sVendors.Length == 0)
                sVendors = selectedItem.Value;
            else
                sVendors = sVendors + "," + selectedItem.Value;

        }
    }

    foreach (ListItem oItem in skill.Items)
    {
        if (oItem.Selected)
        {
            if (sSkill.Length == 0)
                sSkill = oItem.Value;
            else
                sSkill = sSkill + "," + oItem.Value;

        }
    }
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;               
            cmd.CommandText = "INSERT INTO [empdetails] VALUES(@empname, @empcode, @department,@salary, @gender, @sSkill,@sVendors)";
            cmd.Parameters.AddWithValue("@empname", empname);
            cmd.Parameters.AddWithValue("@empcode", empcode);
            cmd.Parameters.AddWithValue("@department", department);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@gender", gender);
            cmd.Parameters.AddWithValue("@sSkill", sSkill);
            cmd.Parameters.AddWithValue("@sVendors", sVendors);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "delete from empdetails where empno='" + lb.Text + "'";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;

    cmd.ExecuteNonQuery();
    GridView1.EditIndex = -1;
    showgrid();
}
public DataSet PopulateControls()
{
    SqlConnection myConnection = new SqlConnection(con);
    SqlDataAdapter ad = new SqlDataAdapter("SELECT [department] FROM department",
                                                            myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "department");
    return ds;
}
public DataSet PopulateControlslist()
{
    SqlConnection myConnection = new SqlConnection(con);
    SqlDataAdapter ad = new SqlDataAdapter("SELECT [projectname] FROM projects",
                                                            myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "projects");
    return ds;
}
private void ShowNoResultFound(DataTable source, GridView gv)
{
    source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable
    // Bind the DataTable which contain a blank row to the GridView
    gv.DataSource = source;
    gv.DataBind();
    // Get the total number of columns in the GridView to know what the Column Span should be
    int columnsCount = gv.Columns.Count;
    gv.Rows[0].Cells.Clear();// clear all the cells in the row
    gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
    gv.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
    //set No Results found to the new added cell
    gv.Rows[0].Cells[0].Text = "NO RESULT FOUND!";

}

}
       

Row cancel and Edit in GridView

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    showgrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    showgrid();
}
       

Gridview row updating

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
    DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1");
    RadioButtonList rbl = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("RadioButtonList1");
    CheckBoxList chb = (CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList2");
    TextBox tx1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
    TextBox tx2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
    TextBox tx3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
    ListBox llb = (ListBox)GridView1.Rows[e.RowIndex].FindControl("ListBox1");
    string ski = "";
    foreach (ListItem selectedItem in chb.Items)
    {
        if (selectedItem.Selected)
        {
            if (ski.Length == 0)
                ski = selectedItem.Value;
            else
                ski = ski + "," + selectedItem.Value;
        }
    }

    string pro = "";
    foreach (ListItem selectedItem in llb.Items)
    {
        if (selectedItem.Selected)
        {
            if (pro.Length == 0)
                pro = selectedItem.Value;
            else
                pro = pro + "," + selectedItem.Value;

        }
    }
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "update empdetails set empname='" + tx1.Text + "',empcode='" + tx2.Text + "',department='" + ddl.SelectedValue.ToString() + "',salary='" +
    tx3.Text + "',gender='" +
    rbl.SelectedValue.ToString() + "',skill='" + ski + "',project='" + pro + "' where empno='" + lb.Text + "'";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    cmd.ExecuteNonQuery();
    GridView1.EditIndex = -1;
    showgrid();
}
       

Save Gridview footer entered vales

protected void save(object sender, EventArgs e)
{


    Control control = null;

    if (GridView1.FooterRow != null)
    {
        control = GridView1.FooterRow;
    }
    else
    {
        control = GridView1.Controls[0].Controls[0];
    }
    string empname = (control.FindControl("txtempName") as TextBox).Text;
    string empcode = (control.FindControl("txtempcode") as TextBox).Text;
    string department = (control.FindControl("DropDownList2") as DropDownList).Text;
    string salary = (control.FindControl("txtsalary") as TextBox).Text;
    string gender = (control.FindControl("RadioButtonList2") as RadioButtonList).Text;    
    string strConnString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    StringCollection sc = new StringCollection();
    ListBox project = GridView1.FooterRow.FindControl("ListBox2") as ListBox;
    CheckBoxList skill = GridView1.FooterRow.FindControl("CheckBoxList1") as CheckBoxList;
    foreach (ListItem selectedItem in project.Items)
    {
        if (selectedItem.Selected)
        {
            if (sVendors.Length == 0)
                sVendors = selectedItem.Value;
            else
                sVendors = sVendors + "," + selectedItem.Value;

        }
    }

    foreach (ListItem oItem in skill.Items)
    {
        if (oItem.Selected)
        {
            if (sSkill.Length == 0)
                sSkill = oItem.Value;
            else
                sSkill = sSkill + "," + oItem.Value;

        }
    }
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;               
            cmd.CommandText = "INSERT INTO [empdetails] VALUES(@empname, @empcode, @department,@salary, @gender, @sSkill,@sVendors)";
            cmd.Parameters.AddWithValue("@empname", empname);
            cmd.Parameters.AddWithValue("@empcode", empcode);
            cmd.Parameters.AddWithValue("@department", department);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@gender", gender);
            cmd.Parameters.AddWithValue("@sSkill", sSkill);
            cmd.Parameters.AddWithValue("@sVendors", sVendors);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}

       

Grid View row delet with Alert Message

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "delete from empdetails where empno='" + lb.Text + "'";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    cmd.ExecuteNonQuery();
    GridView1.EditIndex = -1;
    showgrid();
}
       

Databound in gridview

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DataRowView drv = e.Row.DataItem as DataRowView;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DropDownList dp = (DropDownList)e.Row.FindControl("DropDownList1");
            DataTable dt = load_department();
              for (int i = 0; i < dt.Rows.Count; i++)
                 {
                      ListItem lt = new ListItem();
                      lt.Text = dt.Rows[i][0].ToString();
                      dp.Items.Add(lt);
                  }
            dp.SelectedValue = drv[3].ToString();
            RadioButtonList rbtnl = (RadioButtonList)e.Row.FindControl("RadioButtonList1");
            rbtnl.SelectedValue = drv[5].ToString();
            CheckBoxList chkb = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
            string[] strSplitArr = ((DataRowView)e.Row.DataItem)["skill"].ToString().Split(',');
            foreach (ListItem oItem in chkb.Items)
            {
                for (int i = 0; i < strSplitArr.Length; i++)
                {
                    if (oItem.Value == strSplitArr[i].Trim())
                    {
                        oItem.Selected = true;
                        break;
                    }
                }
            }
            ListBox llb = (ListBox)e.Row.FindControl("ListBox1");
            string[] strSplit = ((DataRowView)e.Row.DataItem)["project"].ToString().Split(',');
            foreach (ListItem oItem in llb.Items)
            {
                for (int i = 0; i < strSplit.Length; i++)
                {
                    if (oItem.Value == strSplit[i].Trim())
                    {
                        oItem.Selected = true;
                        break;
                    }
                }
            }
        }

        string empno = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "empno"));
        LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("btndelete");
        lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + empno + "')");
    }
}
       

load department

public DataTable load_department()
{
    DataTable dt = new DataTable();
    sqlcon = new SqlConnection(con);
    sqlcon.Open();
    string sql = "select * from department";
    SqlCommand cmd = new SqlCommand(sql);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = sqlcon;
    SqlDataAdapter sd = new SqlDataAdapter(cmd);
    sd.Fill(dt);
    return dt;
}
       

empty gridview display Header and footer

private void ShowNoResultFound(DataTable source, GridView gv)
{
    source.Rows.Add(source.NewRow()); // create a new blank row to the DataTable
    // Bind the DataTable which contain a blank row to the GridView
    gv.DataSource = source;
    gv.DataBind();
    // Get the total number of columns in the GridView to know what the Column Span should be
    int columnsCount = gv.Columns.Count;
    gv.Rows[0].Cells.Clear();// clear all the cells in the row
    gv.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
    gv.Rows[0].Cells[0].ColumnSpan = columnsCount;
    //set No Results found to the new added cell
    gv.Rows[0].Cells[0].Text = "NO RESULT FOUND!";

}

       

data for dropdown and listbox

public DataSet PopulateControls()
{
    SqlConnection myConnection = new SqlConnection(con);
    SqlDataAdapter ad = new SqlDataAdapter("SELECT [department] FROM department",
                                                            myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "department");
    return ds;
}
public DataSet PopulateControlslist()
{
    SqlConnection myConnection = new SqlConnection(con);
    SqlDataAdapter ad = new SqlDataAdapter("SELECT [projectname] FROM projects",
                                                            myConnection);
    DataSet ds = new DataSet();
    ad.Fill(ds, "projects");
    return ds;
}
       

check duplicate value entry in grid view

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string CheckUserName(string args)
{
    string returnValue = string.Empty;
    string conString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    SqlConnection sqlConn = new SqlConnection(conString);
    try
    {
        SqlCommand sqlCmd = new SqlCommand("CheckUserName", sqlConn);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@empcode", args.Trim());
        sqlConn.Open();
        int success = int.Parse((sqlCmd.ExecuteScalar().ToString()));
        if (success == 1) // User Name Not Available
        {
            returnValue = "'" + args + "' is already in use.";

        }
        else if (success == 0)//User_Name is available
        {
            returnValue = "Available";
        }
    }
    catch
    {
        //Handle Error
    }
    finally
    {
        sqlConn.Close();
    }

    return returnValue;
}

}

       

javascript validation for textboxes checkbox and listbox in gridview

function ValidateGrid()
{
txtempName = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempName")).ClientID%>');
txtempcode = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempcode")).ClientID %>');
DropDownList2 = document.getElementById('<%=((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).ClientID%>');
txtsalary = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtsalary")).ClientID %>');
//listItemArray = document.getElementById('<%=((RadioButtonList)GridView1.FooterRow.FindControl("RadioButtonList2")).ClientID %>');

if(txtempName.value == 0)
{
alert("Please enter name...!");
txtempName.focus();
return false;
}
if(txtempcode.value == 0)
{
alert("Please Enter Emp code...!");
txtempcode.focus();
return false;
}
var str='';

var Grid_Table = document.getElementById('<%= GridView1.ClientID %>');
var SearchText = document.getElementById('<%=((TextBox)GridView1.FooterRow.FindControl("txtempcode")).ClientID %>').value;
var lenth =Grid_Table.rows.length;
if(lenth > 3)
{
for(var row=1; row<Grid_Table.rows.length-1; row++)
{
for(var col=0; col<Grid_Table.rows[row].cells.length; col++)
{
if(col==0)
 if(document.all[col])
  str=str+Grid_Table.rows[row].cells[2].innerText;
}
} 
}          str=str+'\n'; 
   var array=str.split(" "); 
   for(i = 0; i < array.length; i ++)

{ 

if(array[i] == SearchText)
{
//break;
alert("empcode  already exist");
return false;
}
}
if(DropDownList2.value == 0)
{
alert("Please select ...!");
DropDownList2.focus();
return false;
}
if(txtsalary.value == 0)
{
alert("Please Enter salary...!");
txtsalary.focus();
return false;
}
var numericExpression = /^[0-9]+$/;
if(txtsalary.value.match(numericExpression)){
return true;
}else{
alert("enter Number only");
txtsalary.focus();
return false;
}
var BaseControl = null;
BaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
if (BaseControl == null)
return false;           
var ChildControl = "CheckBoxList1";
var Inputs = BaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
 if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(ChildControl, 0) >= 0 && Inputs[n].checked)
  var valid= true;
if(!valid)
{
alert('Select at least one Skill..!');
 return false;
 
}

var grid = document.getElementById('<%= GridView1.ClientID %>');
var rlength=grid.rows.length;
var clength=rlength-1;
var proj=grid.rows[clength].cells[7].childNodes[0];
for(i = 0; i < proj.length; i++) 
{
if(proj[i].selected)
{
var isvalid=true;
break;
}
    }
if(!isvalid){
alert("select atleast one project..! "); 
return false;
}
return true;
} 

       

Delete confirmation with id

function ConfirmationBox(empno) {
var result = confirm('Are you sure you want to delete '+empno+' employee id Details' );
if (result) {
return true;
}
else {
return false;
}
}
       

Skill validation

function Checkskill(sender, args)
{
BaseContrl = document.getElementById('<%= this.GridView1.ClientID %>');
var ChildContro = "CheckBoxList2";
var Inputs1 = BaseContrl.getElementsByTagName("input");
var ischecked=false;
args.IsValid =false;
for(i=0;i<Inputs1.length;i++)
{
var opt = Inputs1[i];
if(opt.type=="checkbox" && opt.id.indexOf(ChildContro, 0) >= 0 && opt.checked)
{
if(opt.checked)
{
    ischecked= true;
    args.IsValid = true;                
}
}
}

}