Sunday, 29 April 2012

How to delete row in gridview with the help of checkbox?


Here we will shows how to delete multiple records from a GridView using a CheckBox in ASP.NET. This article is helpful in situations where  user can delete row from the database.  I have created a database named mailing in which we have a table named panku.




Here we will create database in sql server.... 
Database name----mailing
Create New table name and field name with datatype and use in application ...
Tablename---panku

Field name---Mail_id—Primarykey(varchar(50))

                         Mail       (varchar(50)

                           Mail_date(datetime)

Impliment design in Default.aspx page :-
  1. Drag and Drop a GridView Control from the toolbox and set AutoGenerateColumns to false.
  2. Add the Columns Collection that manages the collection of column fields.
  3. Add TemplateField inside the Columns Collection that is used to display custom content in a data-bound control.
  4. Add an ItemTemplate in the TemplateField that specifies the content to display for the items in a TemplateField.
  5. Add a CheckBox control inside the ItemTemplate.
  6. Inside the Columns tag, we have added a column field BoundField that displays the value of a field in a data source.
Add a Button Control (ID="Button2) for deleting the selected/checked records.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"

CellPadding="4" AutoGenerateColumns="False" DataKeyNames="Mail_id"

Width="577px"  ForeColor="#333333" GridLines="None"

Height="59px" PageSize="2">



<Columns>

<asp:CommandField ShowSelectButton="True" />

<asp:BoundField DataField="Mail_id" HeaderText="Mail_Id" InsertVisible="False" ReadOnly="True" />

<asp:BoundField DataField="Mail" HeaderText="Mail"  />

<asp:BoundField DataField="M_date" HeaderText="Mail_date"  />



<asp:TemplateField HeaderText="Select">

<ItemTemplate>





<asp:CheckBox ID="chkSelect" runat="server" />    </ItemTemplate>  <HeaderTemplate>

<%--<input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />--%>



</HeaderTemplate>

</asp:TemplateField>

</Columns>

<FooterStyle BackColor="#2A1C38" />

<HeaderStyle VerticalAlign="Top" Wrap="False" BackColor="#2A1C38"

ForeColor="White" />

</asp:GridView>

<br />

<br />        <asp:Button ID="Button2" runat="server" OnClick="Button1_Click" Text="Delete"  BackColor="#1F4983" ForeColor="White"/>

Here we will implement code in Default.aspx.cs page....

protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

           



            BindGridView();





        }

    }

private void BindGridView()

    {

        SqlDataAdapter ad = new SqlDataAdapter("select * from panku order by Mail_id", con);

        DataSet ds = new DataSet();

        ad.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        foreach (GridViewRow row in GridView1.Rows)

        {

            CheckBox cb = ((CheckBox)(row.FindControl("chkSelect")));

            if (cb != null && cb.Checked)

            {

                string Mailid = (GridView1.DataKeys[row.RowIndex].Value.tostring());

                string sqlstr = "delete from panku where Mail_id='" + Mail_id + "'";                         SqlCommand mycmd;

                mycmd = new SqlCommand(sqlstr, con);

                con.Open();

                mycmd.ExecuteNonQuery();

                BindGridView();

            }

            con.Close();

        }

    }


Sunday, 22 April 2012

How to give the validation ,add ,delete ,update and give the information before delete the record in grid view?

Default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
   <script type="text/javascript">
       function Popinfo(Empname) {

           var result = confirm(' you want to delete ' + Empname + ' panku?');
           if (result) {

               return true;
           }
           else {
               return false;
           }
       }
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="gridpop" DataKeyNames="Emp_id,Empname" runat="server"
        AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
        onrowcancelingedit="gridpop_RowCancelingEdit"
        onrowdeleting="gridpop_RowDeleting" onrowediting="gridpop_RowEditing"
        onrowupdating="gridpop_RowUpdating"
        onrowcommand="gridpop_RowCommand" Height="14px" Width="901px"
        onrowdatabound="gridpop_RowDataBound1" BorderWidth="1px" CellPadding="5">
    
    <AlternatingRowStyle Wrap="False" />
    
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="img1update" CommandName="Update" runat="server" ImageUrl="~/Edit.gif" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgcancel" runat="server" CommandName="Cancel" ImageUrl="~/close.png" ToolTip="Cancel" Height="20px" Width="20px" />

</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="editi" CommandName="Edit" runat="server" ImageUrl="~/Edit.gif" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="deletei" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Delete.gif" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="addi3" runat="server" ImageUrl="~/view_icon.gif" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />

</FooterTemplate>
 </asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<EditItemTemplate>
<asp:Label ID="emplbl" runat="server" Text='<%#Eval("Empname") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="emplbl" runat="server" Text='<%#Eval("Empname") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="Empname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="Empname"  ErrorMessage="fill Emp name" ValidationGroup="validaiton" ForeColor="Red"/>
</FooterTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="Password">
 <EditItemTemplate>
 <asp:TextBox ID="passtxt" runat="server" Text='<%#Eval("Password") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="passtxt" runat="server" Text='<%#Eval("Password") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="passwordtxt" runat="server"/>
 <asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="passwordtxt"  ErrorMessage="Fill Password" ForeColor="Red" ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="Email Id">
 <EditItemTemplate>
 <asp:TextBox ID="emailtxt" runat="server" Text='<%#Eval("Email_id") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="emailtxt" runat="server" Text='<%#Eval("Email_id") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="Email_Idtxt" runat="server"/>
  <asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="Email_Idtxt"  ErrorMessage="Fill Email Id" ForeColor="Red"  ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>




 </Columns>

 <EditRowStyle Wrap="False" />
    <FooterStyle Wrap="False" />

<HeaderStyle BackColor="#0061AE" Font-Bold="False" ForeColor="White" Wrap="False"></HeaderStyle>
    <PagerStyle Wrap="False" />
    <RowStyle Wrap="False" />
    <SelectedRowStyle Wrap="False" />
 </asp:GridView>
 <div align="center">
<asp:Label ID="lblresult" runat="server"></asp:Label>
   
    </div>
</asp:Content>




Default.aspx.cs


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

public partial class _Default : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Give connection string");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindpanku();
}
}

protected void Bindpanku()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from panku", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
    gridpop.DataSource = ds;
gridpop.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gridpop.DataSource = ds;
gridpop.DataBind();
int columncount = gridpop.Rows[0].Cells.Count;
gridpop.Rows[0].Cells.Clear();
gridpop.Rows[0].Cells.Add(new TableCell());
gridpop.Rows[0].Cells[0].ColumnSpan = columncount;
gridpop.Rows[0].Cells[0].Text = "No Records Found";
}

}

protected void gridpop_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int Emp_id = Convert.ToInt32(gridpop.DataKeys[e.RowIndex].Value.ToString());
string Empname = gridpop.DataKeys[e.RowIndex].Values["Empname"].ToString();
TextBox emailtxt1 = (TextBox)gridpop.Rows[e.RowIndex].FindControl("emailtxt");

       
       

con.Open();
SqlCommand cmd = new SqlCommand("update panku set  Email_id='" + emailtxt1.Text + "'   where Emp_id=" + Emp_id, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = Empname + " Details Updated successfully";
gridpop.EditIndex = -1;
Bindpanku();
}
protected void gridpop_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridpop.EditIndex = -1;
Bindpanku();
}
protected void gridpop_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
 int Emp_id = Convert.ToInt32(gridpop.DataKeys[e.RowIndex].Values["Emp_id"].ToString());
string Empname = gridpop.DataKeys[e.RowIndex].Values["Empname"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from panku where Emp_id=" + Emp_id, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
Bindpanku();
lblresult.ForeColor = Color.Red;
lblresult.Text = Empname + " details deleted successfully";
}
}
protected void gridpop_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
    TextBox Empname1 = (TextBox)gridpop.FooterRow.FindControl("Empname");
    TextBox passwordtxt1 = (TextBox)gridpop.FooterRow.FindControl("passwordtxt");
    TextBox Email_Idtxt1 = (TextBox)gridpop.FooterRow.FindControl("Email_Idtxt");
          

con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into panku(Empname,password,Email_id,) values('" + Empname1.Text + "','" +
passwordtxt1.Text + "','" + Email_Idtxt1.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
Bindpanku();
lblresult.ForeColor = Color.Green;
lblresult.Text = Empname1.Text + " panku inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = Empname1.Text + " panku not inserted";
}


}


}
protected void gridpop_RowDataBound1(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      
        string Empname = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Empname"));

        ImageButton result = (ImageButton)e.Row.FindControl("deletei");

        if (result != null)
        {
            result.Attributes.Add("onclick", "javascript:return Popinfo('" + Empname + "')");
        }

    }
}
protected void gridpop_RowEditing(object sender, GridViewEditEventArgs e)
{
    gridpop.EditIndex = e.NewEditIndex;
    Bindpanku();
}

}

What is ASP.NET? Components of ASP.NET

ASP.Net Definition -It is used for creating web-based applications.ASP.Net is a web development platform provided by Microsoft. ASP.NET i...