Grid View



Event
Description
PageIndexChanged
Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation.
PageIndexChanging
Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation.
RowCancelingEdit
Occurs when a row's Cancel button is clicked, but before the GridView control exits edit mode.
RowCommand
Occurs when a button is clicked in the GridView control.
RowCreated
Occurs when a new row is created in the GridView control.
RowDataBound
Occurs when a data row is bound to data in the GridView control. This event is often used to modify the contents of a row when the row is bound to data.
RowDeleted
Occurs when a row's Delete button is clicked, but after the GridView control deletes the record from the data source.
RowDeleting
Occurs when a row's Delete button is clicked, but before the GridView control deletes the record from the data source.
RowEditing
Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode.
RowUpdated
Occurs when a row's Update button is clicked, but after the GridView control updates the row.
RowUpdating
Occurs when a row's Update button is clicked, but before the GridView control updates the row.
SelectedIndexChanged
Occurs when a row's Select button is clicked, but after the GridView control handles the select operation
Selected Index Changing
Occurs when a row's Select button is clicked, but before the GridView control handles the select operation.
Sorted
Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation.
Sorting
Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.






How to gridview bind to database?
Step-1

Take a Grid View on aspx page.


Step-2

Write code as following

using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;

using System.Data.SqlClient;

public partial class GridviewBindingTODB : System.Web.UI.Page
{
    string constring = ConfigurationManager.ConnectionStrings["MyWebConfigString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridViewBind();
        }

    }
    private void GridViewBind()
    {
        SqlConnection conn = new SqlConnection(constring);

        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from producttable", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}
OUTPUT







In Grid view Select Row Item Using C# in ASP.Net 3.5.
Bind the Grid View Control using C# code to display the items and implement the Select Command functionality. Grid View Command Field provides the automated functionality to execute the Select command and change the appearance of selected row item, as shown below
Step-1
Create table(Person) in DB

Step-2
Create new aspx page(SelectRowExample.aspx)
First of all drag the Grid View control from Data controls menu.
 It will add the Grid View control HTML source code as given above.
 
<asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

Step-3
  Templates Used
1.    CommandField-àAdd command field(Select)& sets the properties



































2     .SelectedRowStyle

Select Grid view -àPropertes-à SelectedRowStyle


 Grid View provides the auto Generate Select Button property that accepts true or false. If auto Generate Select Button property is set to true then Grid View Control automatically renders the select button at runtime to select the row item. You can also use the Grid View Command Field column to handle the GridView Select command. When you specify a command as select for Command Field or auto Generate Select Button="true" Grid View control automatically handles the event to change the selected Row Index.

In this Example for Grid View Control Select Row, we have used the database.mdf SQL database.
Step-4
After setting Command Field  & Selected Row Style HTML code like this

HTML Source code for Grid view Select Row Example
<form id="form1" runat="server">
  
    <br />
    <asp:GridView ID="GridView1" runat="server">
        <Columns>
<asp:CommandField HeaderText="Select"
                              ShowHeader="True"
                              ShowSelectButton="True">
                <HeaderStyle HorizontalAlign="Left" /> 
                </asp:CommandField>
        </Columns>

         <SelectedRowStyle  BackColor="Yellow" Font-Bold="True" BorderStyle="Inset" />

    </asp:GridView>
  
    </form>
Step-5
CSharp(C#) Source code for Grid view Paging & Sorting
(SelectRowExample.aspx.CS)

 using System.Data.SqlClient;//add namespace

public partial class SelectRowExample : System.Web.UI.Page
{
    string constring = ConfigurationManager.ConnectionStrings["MyWebConfigString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        // The Page is accessed for the first time.
        if (!IsPostBack)
        {
           // Populate the GridView.          
            BindGridView();
        }
    }
    private void BindGridView()
    {
        SqlConnection conn = new SqlConnection(constring);


        // Create a SqlCommand object.
        // Create a SELECT query.
        SqlCommand cmd = new SqlCommand("select * from person", conn);
   
        // Create a SqlDataAdapter object
        // SqlDataAdapter represents a set of data commands and a 
        // database connection that are used to fill the DataSet and 
        // update a SQL Server database. 
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        // Create a DataSet object.
        DataSet ds = new DataSet();

        // Open the connection
        conn.Open();

        // Fill the DataTable named "Person" in DataSet with the rows
        //da.Fill(ds, "Person");
        da.Fill(ds);

        // Bind the GridView control.
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
}
Output:
Build--àRun





Paging & Sorting Using C# in ASP.Net 3.5 Grid view.
ASP.Net 3.5 provides the sorting feature also in Grid View Control. You can Paging & sort the records displayed using Grid view control in ascending or descending order retrieved from SQL database. You can use CSharp code to bind the SQL data with Grid View control and follow the following simple steps to make your ASP.Net Grid View control with sorting enabled. 
 Paging & Sorting Event
Ø  onpageindexchanging="GridView1_PageIndexChanging"
Ø  onsorting="GridView1_Sorting"
Step-1
Create table(Person) in DB


Step-2
Create new aspx page(Paging&SortingExample.aspx)
First of all drag the Grid View control from Data controls menu.
 It will add the Grid View control HTML source code as given above.
 
<asp:GridView ID="GridView2" runat="server">
    </asp:GridView>
Step-3
 Now click on Grid View control to load the control properties at right side panel.

To allow the paging & sorting in Grid View control select True from the dropdown list of Allow Paging & Allow Sorting property of Grid view as shown in above image.
This will add AllowPaging="True" & also set PageSize=5 or 10 or15 Value as per your requirement AS WELL AS & AllowSorting="True" in HTML source code of Grid View Control.
You can set Pager Setting  value as follow

Step-4
Next step is to bind the Paging & Sorting event for Grid View Control.

To bind the Paging & Sorting event of Grid View control, double click on the Sorting event in the properties viewer of Grid View. This will add the Sorting event in the HTML source code and C# code for Grid view.
HTML Source code for Grid view Paging & Sorting
<asp:GridView ID="GridView1" runat="server"
              AllowPaging="True"
              AllowSorting="True"
              onpageindexchanging="GridView1_PageIndexChanging"
              onsorting="GridView1_Sorting"
              PageSize="4">
<PagerSettings Mode="NumericFirstLast" />
</asp:GridView>
Step-5
 CSharp(C#) Source code for Grid view Paging & Sorting
(Paging&SortingExample.aspx.CS)

string constring = ConfigurationManager.ConnectionStrings["MyWebConfigString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        // The Page is accessed for the first time.
        if (!IsPostBack)
        {
            // Enable the GridView paging option and 
            GridView1.AllowPaging = true;
            // specify the page size.
            GridView1.PageSize = 5;

            // Initialize the sorting expression. 
            ViewState["SortExpression"] = "PersonID ASC";

            // Populate the GridView.          
            BindGridView();

        }
    }
    private void BindGridView()
    {
        SqlConnection conn = new SqlConnection(constring);

        // Open the connection
        conn.Open();

        // Create a SqlCommand object.
        // Create a SELECT query.
       SqlCommand cmd = new SqlCommand("select * from person", conn);
     // SqlCommand cmd = new SqlCommand("SP_SelectPerson", conn);

        // Create a SqlDataAdapter object
        // SqlDataAdapter represents a set of data commands and a 
        // database connection that are used to fill the DataSet and 
        // update a SQL Server database. 
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        // Create a DataSet object.
        DataSet ds = new DataSet();

// if I wrire like this  da.Fill(ds); I got error

//Object reference not set to an instance of an object.

//so don’t forget write like this

 

        // Fill the DataTable named "Person" in DataSet with the rows
       da.Fill(ds, "Person");

 

        // Get the DataView from Person DataTable.
        DataView dv = ds.Tables["Person"].DefaultView;
        // Set the sort column and sort order.
        dv.Sort = ViewState["SortExpression"].ToString();

        // Bind the GridView control.
        GridView1.DataSource = dv;
        GridView1.DataBind();

    }

//for PageIndex Changing
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        // Populate the GridView.
        BindGridView();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');

        // If the sorting column is the same as the previous one,  
        // then change the sort order. 
        if (strSortExpression[0] == e.SortExpression)
        {
            if (strSortExpression[1] == "ASC")
            {
                ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
            }
        }
        // If sorting column is another column,   
        // then specify the sort order to "Ascending". 
        else
        {
            ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
        }

        // Rebind the GridView control to show sorted data. 
        BindGridView(); 
    }
Output:
Build--àRun




Grid view Row Deleting Using C# in ASP.Net 3.5.
ASP.Net Grid View control provides a Command Field that enables you to display the Delete Command button. You can easily attach the Grid View event such as Row Deleting to implement the delete command of Grid View control.
Row Deleting Event
Ø  onrowdatabound="GridView1_RowDataBound"
Ø  onrowdeleting="GridView1_RowDeleting"
Step-1
Create table(Person) in DB


Step-2
Create new aspx page(DeleteExample.aspx)
First of all drag the Grid View control from Data controls menu.
 It will add the Grid View control HTML source code as given above.
 
<asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
Step-3
Then you have to set grid view task as shown below

You have to add command fieldà 1) Edit,Update,Cancel &  2)Delete(Must be add both )

 

Step-4
After that you have to set Grid view EVENT as follow
Grid view1 (Right Click)--àEvent-à 1) RowDeleting 2)RowDataBound

HTML Source code for Grid view Row Deleting
<form id="form1" runat="server">
    <br />
    <br />

    <asp:GridView ID="GridView1" runat="server"
         onrowdatabound="GridView1_RowDataBound"
         onrowdeleting="GridView1_RowDeleting">                       
        <Columns>
            <asp:CommandField ShowEditButton="True" />
            <asp:CommandField ShowDeleteButton="True" />
        </Columns>
    </asp:GridView>
    
    </form>
Step-5

CSharp(C#) Source code for Grid view Row Deleting
(Row DeletingExample.aspx.CS)

using System.Data.SqlClient;

public partial class DeleteExamples : System.Web.UI.Page
{
    string constring = ConfigurationManager.ConnectionStrings["MyWebConfigString"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        // The Page is accessed for the first time.
        if (!IsPostBack)
        {
            // Populate the GridView.          
            BindGridView();
        }
    }
    private void BindGridView()
    {
        // Get the connection string from Web.config. 
        // When we use Using statement, 
        // we don't need to explicitly dispose the object in the code, 
        // the using statement takes care of it.
        SqlConnection conn = new SqlConnection(constring);

        // Open the connection
        conn.Open();

        // Create a SELECT query.
        SqlCommand cmd = new SqlCommand("SELECT PersonID,LastName,FirstName FROM Person", conn);

        // Create a SqlDataAdapter object
        // SqlDataAdapter represents a set of data commands and a 
        // database connection that are used to fill the DataSet and 
        // update a SQL Server database. 
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        // Create a DataSet object.
        DataSet ds = new DataSet();

        // Fill the DataTable named "Person" in DataSet with the rows
        // returned by the query.new n
        //da.Fill(ds, "Person");
        da.Fill(ds);

        //Bind the GridView control.
        //gvPerson.DataSource = dvPerson;
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // Make sure the current GridViewRow is a data row.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Make sure the current GridViewRow is either 
            // in the normal state or an alternate row.
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                // Add client-side confirmation when deleting.
                ((LinkButton)e.Row.Cells[1].Controls[0]).Attributes["onclick"] = "if(!confirm('Are you certain you want to delete this person ?')) return false;";
            }
        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Get the connection string from Web.config. 
        // When we use Using statement, 
        // we don't need to explicitly dispose the object in the code, 
        // the using statement takes care of it.
        SqlConnection conn = new SqlConnection(constring);

        // Open the connection
        conn.Open();

        // Create a command object.
        SqlCommand cmd = new SqlCommand("DELETE FROM Person WHERE PersonID = @PersonID", conn);
        //SqlCommand cmd = new SqlCommand("SP_DeletePerson", conn);

        //// Set the command text
        //// SQL statement or the name of the stored procedure 
        //cmd.CommandText = "DELETE FROM Person WHERE PersonID = @PersonID";


        // Set the command type
        // CommandType.Text for ordinary SQL statements; 
         cmd.CommandType = CommandType.Text;

         //Set the command type
        // CommandType.StoredProcedure for stored procedures.
       // cmd.CommandType = CommandType.StoredProcedure;


        // Get the PersonID of the selected row.
        string strPersonID = GridView1.Rows[e.RowIndex].Cells[2].Text;

        // Append the parameter.
          cmd.Parameters.Add("@PersonID", SqlDbType.Int).Value = strPersonID;
       // cmd.Parameters.AddWithValue("@PersonID", strPersonID);

        // Execute the command.
        cmd.ExecuteNonQuery();

        // Rebind the GridView control to show data after deleting.
        BindGridView();
    }
   
}
Output:
Build--àRun






DropDownList  Binding With DB
Step-1

Create table as citytable


Insert value in table



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 DropDownList : System.Web.UI.Page
{
    string strconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindddlcity();
        }
       
    }
     
  protected   void Bindddlcity()
    {
       
        SqlConnection conn = new SqlConnection(strconn);
        conn.Open();
        SqlCommand cmd = new SqlCommand("select * from citytable ",conn);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        //for DropDownList1 binding
        ddlcity.DataSource = ds;
        ddlcity.DataTextField = "cname";
        ddlcity.DataValueField = "cname";
        ddlcity.DataBind();
        //starting value set
        DropDownList1.Items.Insert(0,"<select>");
      
    }
}

OUTPUT






GridView with CheckBox – Select All and display

STEP-I:-Create new aspx page(GridViewWithCheckBox.aspx)

GridView Tasks---àEdit Columns-àfield wised open as shown below.
Then add Boundfield -àProductID, ProductName, UnitInSystem, PrizePerUnit .


Then add TemplactField as shown below


Then

Then as shown in below

Then add
 Finally show like this

Then write Javascript in source code
<head runat="server">

<script language="javascript">
function SelectAllCheckboxes(spanChk){
// Added as ASPX uses SPAN for checkbox
var oItem = spanChk.children;
var theBox= (spanChk.type=="checkbox") ?
spanChk : spanChk.children.item[0];
xState=theBox.checked;
elm=theBox.form.elements;

for(i=0;i<elm.length;i++)
if(elm[i].type=="checkbox" &&
elm[i].id!=theBox.id)
{
//elm[i].click();
if(elm[i].checked!=xState)
elm[i].click();
//elm[i].checked=xState;
}
}
</script>
<title>Untitled Page</title>
</head>
Just add function
<asp:TemplateField HeaderText="Select " >
<HeaderTemplate>
&nbsp;
<asp:Label ID="Label1" runat="server" Text="Select All"></asp:Label>
<input ID="chkAll" runat="server"
onclick="javascript:SelectAllCheckboxes(this);" title="Select"
type="checkbox" />

</HeaderTemplate>
<ItemTemplate>
<%--this checkbox id write in FindControl("CheckBox1")--%>
<asp:CheckBox ID="CheckBox3" runat="server" />
&nbsp;
</ItemTemplate>
Then
string constring = ConfigurationManager.ConnectionStrings["MyWebConfigString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridBind();

        }
    }
    private void GridBind()
    {
        SqlConnection conn = new SqlConnection(constring);
 SqlCommand cmd = new SqlCommand("select * from producttable", conn);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // StringBuilder object

        StringBuilder str = new StringBuilder();
        // Select the checkboxes from the GridView control

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            bool isChecked = ((CheckBox)row.FindControl("CheckBox3")).Checked;
           // bool isChecked = ((CheckBox)row.FindControl("LinkButton2")).Checked;
            if (isChecked)
            {
  // Column 2 is the name column to change Cells[1,2,3,4,5 like this]

                str.Append(GridView1.Rows[i].Cells[4].Text);
            }
        }
        // prints out the result in TextBox1
        TextBox1.Text = str.ToString();
        Response.Write(str.ToString());

        // prints out the result in GridView2
        //GridBind1();


    }



Check OUTPUT




Select Multiple CheckBox For Delete data form database




<%@ Page Title="" Language="C#" MasterPageFile="~/UserArea/UserArea.master" AutoEventWireup="true" CodeFile="Inbox3.aspx.cs" Inherits="UserArea_Inbox3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <script language="javascript">
    function SelectAllCheckboxes(spanChk) {
        // Added as ASPX uses SPAN for checkbox
        var oItem = spanChk.children;
        var theBox = (spanChk.type == "checkbox") ?
spanChk : spanChk.children.item[0];
        xState = theBox.checked;
        elm = theBox.form.elements;

        for (i = 0; i < elm.length; i++)
            if (elm[i].type == "checkbox" &&
elm[i].id != theBox.id) {
                //elm[i].click();
                if (elm[i].checked != xState)
                    elm[i].click();
                //elm[i].checked=xState;
            }
    }
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div align="center">
        <asp:GridView ID="GrdReport" runat="server" AutoGenerateColumns="False" Width="50%"
            BackColor="White" CellPadding="4" ForeColor="Black" GridLines="Vertical" DataKeyNames="compid"
            OnRowDataBound="Grd_Download_RowDataBound" CssClass="BugGridview "
            OnSelectedIndexChanged="GrdReport_SelectedIndexChanged" AllowPaging="True"
            onpageindexchanging="GrdReport_PageIndexChanging">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
              <%--<asp:TemplateField>
                <HeaderTemplate>
                        <input ID="chk123" runat="server" onclick="javascript:SelectAllCheckboxes(this);" title="Select" type="checkbox" />
                       <asp:Label ID="Label1" runat="server" Text="Select All"></asp:Label>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox3" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>--%>
                <asp:TemplateField><HeaderTemplate>
                        <input ID="chk123" runat="server" onclick="javascript:SelectAllCheckboxes(this);" title="Select" type="checkbox" />
                       <asp:Label ID="Label1" runat="server" Text="Select All"></asp:Label>
                </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="chk123" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Compid">
                    <ItemTemplate>
                        <asp:Label ID="lblBugId" runat="server" Text='<%#Bind("compid")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="From">
                    <ItemTemplate>
                        <asp:Label ID="lblBugName" runat="server" Text='<%#Bind("ActionBy") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Subject">
                    <ItemTemplate>
                        <asp:Label ID="lblBugDescription" runat="server" Text='<%#Bind("Subject") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Attachments">
                    <ItemTemplate>
                        <%--   <asp:LinkButton ID="lbtnAttachments" runat="server" Text="Download" Font-Underline="true"></asp:LinkButton>--%>
                        <asp:HyperLink ID="Hyplnk_Attachments" runat="server" Font-Underline="true" NavigateUrl='<%# Eval("compid", "GetFile.aspx?ID={0}&Attachmentid=1") %>'
                            Text="Download" ForeColor="Blue"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Status">
                    <ItemTemplate>
                        <asp:LinkButton ID="lbtnStatus" runat="server" Text="View" Font-Underline="true"
                            CommandName="Select"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Action">
                    <ItemTemplate>
                        <asp:LinkButton ID="lbtnEdit" runat="server" Text="Edit" CommandName="Edit" Font-Underline="true"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle CssClass="BugGridHeader " />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#F7F7DE" />
            <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FBFBF2" />
            <SortedAscendingHeaderStyle BackColor="#848384" />
            <SortedDescendingCellStyle BackColor="#EAEAD3" />
            <SortedDescendingHeaderStyle BackColor="#575357" />
        </asp:GridView>
    </div>
    <table>
        <tr>
            <td>
                <asp:Button ID="btn" runat="server" Text="delete" OnClick="btn1_Click" />
            </td>
            <td>
               <%-- <headertemplate> <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images.jpg"  Height="20px" Width="24px"
                onclick="btn1_Click" /></headertemplate>--%>
            </td>
        </tr>
    </table>
</asp:Content>




In C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Specialized;
using System.Text;
using System.Collections;

public partial class UserArea_Inbox3 : System.Web.UI.Page
{
    string constring = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

    DataSet ds = new DataSet();

    string r;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridViewBind();
        }
    }

    private void GridViewBind()
    {
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand cmd = new SqlCommand("Select * from Compose", conn);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        ad.Fill(ds, "compose");
        GrdReport.DataSource = ds;
        GrdReport.DataBind();
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        StringCollection sc = new StringCollection();
        //for (int i = 0; i < GrdReport.Rows.Count; i++)
            foreach (GridViewRow gvrow in GrdReport.Rows)
        {
            CheckBox cb = (CheckBox)gvrow.FindControl("chk123"); //find the CheckBox
            //CheckBox cb = (CheckBox)GrdReport.FindControl("chk123"); //find the CheckBox
            if (cb != null)
            {
                if (cb.Checked)
                {
                    int usrid = Convert.ToInt32(GrdReport.DataKeys[gvrow.RowIndex].Value);
                    //string id = GrdReport.Rows[i].Cells[1].Text;  
                    sc.Add(usrid.ToString());
                    //sc.Add(id.ToString());
                    DeleteRecords(sc);
                }
            }
        }
        GridViewBind();
    }
    private void DeleteRecords(StringCollection sc)
    {
        SqlConnection conn = new SqlConnection(constring);
        //StringBuilder sb = new StringBuilder(string.Empty);         
        try
        {
            conn.Open();
            foreach (string item in sc)
            {

                //SqlCommand cmd = new SqlCommand("delete from compose where compid=" + item, conn);
                //cmd.ExecuteNonQuery();

                SqlConnection con = new SqlConnection(constring);
                SqlCommand cmd = new SqlCommand("Delete_Inbox_SP", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@compid", item);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
              
                con.Close();



            }
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Deletion Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }
    protected void Grd_Download_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //int id = Convert.ToInt16((e.Row.FindControl("lblBugId") as Label).Text);

            //Functions objfn = new Functions();
            //DataTable file = new DataTable();

            //file = objfn.GetAFile(id);
            //DataRow row = file.Rows[0];

            //if (file.DefaultView[0]["AttachmentName"].ToString().Trim() == "")
            //{
            //    (e.Row.FindControl("Hyplnk_Attachments") as HyperLink).Visible = false;
            //}

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

     }
    
     protected void GrdReport_PageIndexChanging(object sender, GridViewPageEventArgs e)
     {
         GrdReport.PageIndex = e.NewPageIndex;
         GridViewBind();

     }
}


Note:-For Update purpose just change Stored procedure & method(UpdateRecord) all other are same.

Change stored  procedure query as following screen

CHANGE method update method as following c# code

private void UpdateRecords(StringCollection sc)
    {
        SqlConnection conn = new SqlConnection(constring);
        //StringBuilder sb = new StringBuilder(string.Empty);          
        try
        {
            conn.Open();
            foreach (string item in sc)
            {

                ////SqlCommand cmd = new SqlCommand("delete from compose where compid=" + item, conn);
                //SqlCommand cmd = new SqlCommand("update compose set flage='True' where compid=" + item, conn);
                //cmd.ExecuteNonQuery();
                //using stored procedure
              
                SqlConnection con = new SqlConnection(constring);
                SqlCommand cmd = new SqlCommand("Update_ComposeInbox_SP", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@compid", item);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                int j = cmd.ExecuteNonQuery();

                if (j > 0)
                {
                    lblerror.Text = "Deleted successfully";
                }
                else
                {
                    lblerror.Text = "Not Deleted";

                }
                con.Close();
            }
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Deletion Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }









 How to insert data using radio buttons value in male or female?

For an example I am create simple page in that page I placed a textbox, two radio button for male or female
Client side code
I have places some controls in client side of the web page (is called ExampleOFRadioButton.aspx) and shown in below figure.

Server side
protected void btninsert_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(constring);
        try
        {
            if (TextBox1.Text!=string .Empty &&  RadioButton1.Checked!=false || RadioButton2.Checked!=false )
            {
               conn.Open();
SqlCommand cmd = new SqlCommand("sp_addtbl1", conn);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter eid = new SqlParameter("@eid", System.Data.SqlDbType.BigInt);
SqlParameter ename = new SqlParameter("@ename", System.Data.SqlDbType.VarChar, 50);
SqlParameter gender = new SqlParameter("@gender", System.Data.SqlDbType.Char, 6);
SqlParameter actionby = new SqlParameter("@actionby", System.Data.SqlDbType.VarChar, 50);
SqlParameter actiondate = new SqlParameter("@actiondate", System.Data.SqlDbType.DateTime);

                cmd.Parameters.AddWithValue("@eid", TextBox4.Text);
                cmd.Parameters.AddWithValue("@ename", TextBox1.Text);

                string g = "";
                if (RadioButton1.Checked)
                    g = RadioButton1.Text;
                else
                    g = RadioButton2.Text;

                cmd.Parameters.AddWithValue("@gender", g);

                cmd.Parameters.AddWithValue("@actionby", TextBox1.Text);
                cmd.Parameters.AddWithValue("@actiondate", DateTime.Now);
                cmd.ExecuteNonQuery();
                Response.Write("<script>alert('Record Inserted!!!!!')</script>");

                GridBind();
                ClearAll();
            }
            else
            {
                Response.Write("Please enter all field carfully!!!!");
            }
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            conn.Close();
        }

    }
OUTPUT

Client code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
     <style type="text/css">
        .style1
        {
            width: 344px;
            background-color: #C0C0C0;
            height: 218px;
        }
        .style2
        {
            width: 107px;
        }
        .style4
        {
            width: 149px;
        }
        .style6
        {
            width: 73px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    
    <table class="style1">
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td class="style6">
                <asp:TextBox ID="TextBox4" runat="server" ReadOnly="True" Visible="False"></asp:TextBox>
            </td>
            <td class="style4">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style2">
                Employee Name:</td>
            <td class="style6">
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
            <td class="style4">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style2">
                Gender:</td>
            <td class="style6">
                <asp:RadioButton ID="RadioButton1" runat="server" Text="Male"
                    GroupName="gender" />
            </td>
            <td class="style4">
                <asp:RadioButton ID="RadioButton2" runat="server" Text="Female"
                    GroupName="gender" />
            </td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td class="style6">
                <asp:Button ID="btninsert" runat="server" Height="27px"
                    onclick="btninsert_Click" Text="Insert " Width="108px" />
            </td>
            <td class="style4">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;</td>
            <td class="style6">
                &nbsp;</td>
            <td class="style4">
                <asp:GridView ID="GridView1" runat="server">
                </asp:GridView>
            </td>
        </tr>
        </table>
    <p>
        &nbsp;</p>
    
    </form>
</body>
</html>


No comments:

Tabs


Tab 1 content goes here

Tab 2 content goes here

Tab 3 content goes here
Multi-Tabbed Widget | DotNetIs