Saturday, 10 November 2012

Export selected rows of gridview to Excel or word in ASP.Net


Export selected rows of gridview to Excel or word in ASP.Net

Introduction:

Here I will explain how to export only selected or checked rows or records from gridview to Word or Excel sheet using asp.net.

Description:

In my previous posts I explained clearly how to export gridview data to Excel or word using asp.net and how to export gridview data to PDF using asp.net and explained another post that is Export gridview data to CSV file using asp.net. After explain all the concepts one of the user has asked me a question i.e. how to export gridview records to excel/word based on checkbox selection in gridview. To implement this one first design one table in database as shown below and give name as “UserInformation”


ColumnName

DataType
UserId

Int(set identity property=true)
UserName

varchar(50)
LastName

varchar(50)
Location

varchar(50)
After completion of table creation enter some dummy data and design aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Export Selected records from Gridview to Excel/ Word</title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
.highlight {text-decoration: none;color:black;background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExportExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<div class="GridviewDiv">
<asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" Width="540px" PageSize="10" CssClass="Gridview" DataKeyNames="UserId" OnPageIndexChanging="gvdetails_PageIndexChanging" >
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Now in code behind add following namespace references

using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
After that write the following code in code behind

C# Code



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
/// <summary>
/// This Method is used to bind gridview
/// </summary>
private void BindGridData()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
public override void VerifyRenderingInServerForm(Control control)
{
/*Verifies that the control is rendered */
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCheckedValues();
gvdetails.PageIndex = e.NewPageIndex;
BindGridData();
PopulateCheckedValues();
}
/// <summary>
/// This event is used to export gridview data to Excel document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ExportFunction("attachment;filename=GridViewExport.xls", "application/vnd.ms-excel");
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, EventArgs e)
{
ExportFunction("attachment;filename=GridViewExport.doc", "application/vnd.ms-word");
}
/// <summary>
/// This Function is used to generate Excel or word document with gridview checkbox selected values
/// </summary>
/// <param name="header"></param>
/// <param name="contentType"></param>
private void ExportFunction(string header, string contentType)
{
SaveCheckedValues();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", header);
Response.Charset = "";
Response.ContentType = contentType;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
BindGridData();
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
gvdetails.HeaderRow.Cells[0].Visible = false;
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
gvdetails.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
}
if (ViewState["CHECKED_ITEMS"] != null)
{
ArrayList CheckBoxArray = (ArrayList)ViewState["CHECKED_ITEMS"];
int rowIdx = 0;
for (int i = 0; i < gvdetails.Rows.Count; i++)
{
GridViewRow row = gvdetails.Rows[i];
row.Visible = false;
int index = (int)gvdetails.DataKeys[row.RowIndex].Value;
if (CheckBoxArray.Contains(index))
{
row.Visible = true;
row.Cells[0].Visible = false;
}
}
}
gvdetails.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
}
/// <summary>
///This method is used to populate the saved checked status of checkbox values
/// </summary>
private void PopulateCheckedValues()
{
ArrayList userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
if (userdetails != null && userdetails.Count > 0)
{
foreach (GridViewRow gvrow in gvdetails.Rows)
{
int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
if (userdetails.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
/// <summary>
/// This method is used to save the checkedstate of checkbox values
/// </summary>
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in gvdetails.Rows)
{
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
// Check in the Session
if (ViewState["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
ViewState["CHECKED_ITEMS"] = userdetails;
}

VB.NET Code

Imports System.Collections
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class VBExportData
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
BindGridData()
End If
End Sub
''' <summary>
''' This Method is used to bind gridview
''' </summary>
Private Sub BindGridData()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Dim cmd As New SqlCommand("select * from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvdetails.DataSource = ds
gvdetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'Verifies that the control is rendered
End Sub
Protected Sub gvdetails_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
SaveCheckedValues()
gvdetails.PageIndex = e.NewPageIndex
BindGridData()
PopulateCheckedValues()
End Sub
''' <summary>
''' This event is used to export gridview data to Excel document
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Protected Sub btnExportExcel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnExcel.Click
ExportFunction("attachment;filename=GridViewExport.xls", "application/vnd.ms-excel")
End Sub
''' <summary>
''' This event is used to export gridview data to word document
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Protected Sub btnWord_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnWord.Click
ExportFunction("attachment;filename=GridViewExport.doc", "application/vnd.ms-word")
End Sub
''' <summary>
''' This Function is used to generate Excel or word document with gridview checkbox selected values
''' </summary>
''' <param name="header"></param>
''' <param name="contentType"></param>
Private Sub ExportFunction(ByVal header As String, ByVal contentType As String)
SaveCheckedValues()
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", header)
Response.Charset = ""
Response.ContentType = contentType
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gvdetails.AllowPaging = False
BindGridData()
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
gvdetails.HeaderRow.Cells(0).Visible = False
For i As Integer = 0 To gvdetails.HeaderRow.Cells.Count - 1
gvdetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
gvdetails.HeaderRow.Cells(i).Style.Add("color", "#FFFFFF")
Next
If ViewState("CHECKED_ITEMS") IsNot Nothing Then
Dim CheckBoxArray As ArrayList = DirectCast(ViewState("CHECKED_ITEMS"), ArrayList)
Dim rowIdx As Integer = 0
For i As Integer = 0 To gvdetails.Rows.Count - 1
Dim row As GridViewRow = gvdetails.Rows(i)
row.Visible = False
Dim index As Integer = CInt(gvdetails.DataKeys(row.RowIndex).Value)
If CheckBoxArray.Contains(index) Then
row.Visible = True
row.Cells(0).Visible = False
End If
Next
End If
gvdetails.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.[End]()
End Sub
''' <summary>
'''This method is used to populate the saved checked status of checkbox values
''' </summary>
Private Sub PopulateCheckedValues()
Dim userdetails As ArrayList = DirectCast(ViewState("CHECKED_ITEMS"), ArrayList)
If userdetails IsNot Nothing AndAlso userdetails.Count > 0 Then
For Each gvrow As GridViewRow In gvdetails.Rows
Dim index As Integer = CInt(gvdetails.DataKeys(gvrow.RowIndex).Value)
If userdetails.Contains(index) Then
Dim myCheckBox As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
myCheckBox.Checked = True
End If
Next
End If
End Sub
''' <summary>
''' This method is used to save the checkedstate of checkbox values
''' </summary>
Private Sub SaveCheckedValues()
Dim userdetails As New ArrayList()
Dim index As Integer = -1
For Each gvrow As GridViewRow In gvdetails.Rows
index = CInt(gvdetails.DataKeys(gvrow.RowIndex).Value)
Dim result As Boolean = DirectCast(gvrow.FindControl("chkSelect"), CheckBox).Checked
' Check in the Session
If ViewState("CHECKED_ITEMS") IsNot Nothing Then
userdetails = DirectCast(ViewState("CHECKED_ITEMS"), ArrayList)
End If
If result Then
If Not userdetails.Contains(index) Then
userdetails.Add(index)
End If
Else
userdetails.Remove(index)
End If
Next
If userdetails IsNot Nothing AndAlso userdetails.Count > 0 Then
ViewState("CHECKED_ITEMS") = userdetails
End If
End Sub
End Class
After that run your application output would be like this

If you observe above code I written code to export selected rows of gridview based on checkbox selection. In previous post I explained clearly how to maintain state of checkboxes in while paging in gridview here I used same concept to maintain the state of checkboxes while paging in gridview and I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”.

If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly. Here I used simple code to export gridview data to excel document and for word document we can use the same code (Export to Word) to import gridview data just by replacing GridViewExport.xls to GridViewExport.doc and application/ms-excel to application/ms-word

Demo

Now select checkboxes and click on Excel button you will get output like this

Demo for Excel document

Demo for Word document

Export gridview data to Excel/word document in asp.net


Export gridview data to Excel/word document in asp.net

Introduction:

Here I will explain how to export gridview to Word or Excel document using asp.net.

Description:

I have one gridview that has filled with user details now I need to export gridview data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails"  AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsdetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"/>
</div>
</form>
</body>
</html>
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
After set the connection string in web.config file now we are able to get the data from database and we can bind that data to gridview by using sqldatasource. Now if you run application gridview appears like this

                                                   




Now in code behind add this reference
using System.IO;
After that write the following code in code behind



public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, ImageClickEventArgs e)
{
gvdetails.AllowPaging = false;
gvdetails.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
/// <summary>
/// This Event is used to export gridview data to Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Demo for Word document

If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.
Here I used basic code to export gridview data to word document and for excel code is different but we can use the same code (Export to Word) for excel also to import gridview data just by replacing Customers.doc to Customers.xls and application/ms-word to application/ms-excel but here we have problem that is row background color is applied throughout excel for that reason I made some small code modification and applied color only to the particular columns based on rows.

Demo for Excel document



















Thursday, 8 November 2012

JQGrid in DotNet Application


JQGrid in DotNet Application

JQGrid is one of the most popular HTML grid implementation available out there. It provides multiple facilities like inline edit, searching, sorting, multiple select, sub grid etc. JQGrid can be implemented in 2 ways
Load Once (Load the whole data at the time of page load and then make a grid out of it)
Ajax Request based (Load the data in ajaxified fashion)

Here we would be making Load Once JQGrid in a DotNet application.

To show JQGrid in ASP.net application we need following Steps:-
Fetch data from database into dataset/any collection
Serialize and store that data in a hidden field in JSON format like displayed in the personList shown below.
Parse hidden field data at the client end (script end) and generate JQGrid.
The datasource is a simple a JSON data
var personList = [
    {id:"1",name:"test1",note:"note23",amount:"200.00"},
    {id:"2",name:"test2",note:"note2",amount:"300.00"},
    {id:"3",name:"test3",note:"note32",amount:"400.00"},
    {id:"4",name:"test23",note:"note423",amount:"700.00"},
    {id:"5",name:"test2",note:"note2",amount:"300.00"},
    {id:"6",name:"test333",note:"note344",amount:"500.00"}
]      
In order to get your JQgrid, you would have to add following things in your aspx page (lets say it Person.aspx).

CSS  Basic layout of JQGrid is defined by jquery.ui. You can download the jquery ui from the http://jqueryui.com/ and even customize look and feel using their awesome themeroller (http://jqueryui.com/themeroller/).
    <link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.8.13/themes/base/jquery-ui.css" />
    <link type="text/css" rel="stylesheet" href="http://www.trirand.com/blog/jqgrid/themes/ui.jqgrid.css" />
JS You need to include JQuery, JQuery UI, JQGrid and JQGrid locale file.
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/jquery-ui.js"></script>
    <script type="text/javascript" src="http://www.trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" src="http://www.trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script>
C# Code: In code behind (lets say Person.cs), we need to create a list of maps and serialize this list. After serialization of this list, we need to set it to a hidden field of aspx page (in this case hdnPersonList).
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Web.Script.Serialization;

        private void PopulatePersons()
        {
            DataSet ds = new DataSet();
            ArrayList list = new ArrayList();
            ds = _person.LoadPersons();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
               Hashtable entry = new Hashtable();
               entry.Add("id", dr["personId"].ToString());
               entry.Add("name", dr["name"].ToString());
               entry.Add("note", dr["note"].ToString());
               entry.Add("amount", dr["amount"].ToString());
               list.Add(entry);
            }
            JavaScriptSerializer jserializer = new JavaScriptSerializer();
            hdnPersonList.Value = jserializer.Serialize(list);
        }
HTML code: In your aspx (i.e. Person.aspx) page, add following lines. Here the HiddenField is the control where you are setting the personList passed from backend. tblJQGrid is the id which would be converted into a grid. divPager is the id which would be converted into a pager for your grid.
    <asp:HiddenField ID="hdnPersonList" runat="server" />  
        <table id="tblJQGrid"></table>
        <div id="divPager"></div>
JQuery code: Now lets put the JQGrid creation code in your aspx page (Person.aspx).
<script language="javascript" type="text/javascript">
proceed = true;
try {
    var valOfHidden = $.parseJSON(htmlDecode($("#<%= hdnPersonList.ClientID %>").val()));
}

catch (Exception) {
    proceed = false;
    // Do nothing
}

$(document).ready(function() {
    if (proceed) {
        createUserGrid();
    }
});

function createUserGrid() {
    $("#tblJQGrid").jqGrid({
        data: valOfHidden,
        datatype: "local",
        height: 231,
        width: 937,
        colNames:['Number', 'Name', 'Amount', 'Notes'],
        colModel:[
            {name:'id',index:'id', width:60, sorttype:"int"},
            {name:'name',index:'name', width:100},
            {name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},  
            {name:'note',index:'note', width:150, sortable:false}      
        ],
        //multiselect: true,
        rowNum:10,
        rowList:[10,20,30],
        loadonce: true,
        pager: '#divPager',
        caption: "Users Data"
    });
}

function htmlDecode(value) {
    if (value) {
        return $('<div/>').html(value).text();
    }
}
</script>
Thats it!!!

Compile and refresh your page and now you should see a nice JQGrid as displayed below :). Just, in case it doesn't work, please leave a comment and we can help you





How to create a sample WPF


 How to create a sample WPF Sample Application using C#.Net.
XAML Code :

<Window x:Class="simple_sample_App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="Name" HorizontalAlignment="Left" Margin="157,56,0,0" VerticalAlignment="Top"/>
        <Label Content="Location" HorizontalAlignment="Left" Margin="157,87,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtName" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Margin="233,58,0,0" Width="120"/>
        <TextBox x:Name="txtLocation" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Margin="233,89,0,0" Width="120"/>
        <Button x:Name="btnSubmit" Content="Submit" HorizontalAlignment="Left" Margin="233,126,0,0" VerticalAlignment="Top" Width="75" Click="btnSubmit_Click"/>
        <Label Content="Name" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="157,211,0,0"/>
        <Label Content="Location" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="157,242,0,0"/>
        <Label x:Name="lblName" Content="Label" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="233,211,0,0"/>
        <Label x:Name="lblLocation" Content="Label" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="233,242,0,0"/>
        <Label Content="Result :" HorizontalAlignment="Left" Margin="157,180,0,0" VerticalAlignment="Top"/>
        <Label Content="WPF Sample Application" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="157,10,0,0" FontFamily="Arial Black" FontSize="16"/>

    </Grid>
</Window>

XAML.CS Code :
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace simple_sample_App
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            lblName.Content = txtName.Text;
            lblLocation.Content = txtLocation.Text;
        }
    }
}


OutPut :

How to insert data into Ms Access 2007 using WPF


 How to insert data into Ms Access 2007 using WPF || Inserting and Binding of data to GridView from Ms Access in WPF
XAML Code :

<window height="493" title="MainWindow" width="533" x:class="MoneyWizard.MainWindow" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <grid margin="1,8,2,3" rendertransformorigin="0.463,0.489">
        <label content="Bank Name" horizontalalignment="Left" margin="80,57,0,0" verticalalignment="Top">
            <label .background=".background">
                <imagebrush>
            </imagebrush></label>
        </label>
        <label content="Account Number" horizontalalignment="Left" margin="81,101,0,0" verticalalignment="Top">
        <label content="Account Type" horizontalalignment="Left" margin="82,141,0,0" verticalalignment="Top">
        <label content="Balance" horizontalalignment="Left" margin="81,209,0,0" verticalalignment="Top">
        <combobox horizontalalignment="Left" margin="241,58,0,0" verticalalignment="Top" width="196" x:name="cmbBankName">
            <comboboxitem content="Axis Bank">
            <comboboxitem content="HDFC Bank" horizontalalignment="Left" width="118">
        </comboboxitem></comboboxitem></combobox>
        <textbox horizontalalignment="Left" margin="242,102,0,0" rendertransformorigin="0.5,0.5" textwrapping="Wrap" verticalalignment="Top" width="196" x:name="txtAcNo">
            <textbox .rendertransform=".rendertransform">
                <transformgroup>
                    <scaletransform>
                    <skewtransform>
                    <rotatetransform angle="-7380.224">
                    <translatetransform>
                </translatetransform></rotatetransform></skewtransform></scaletransform></transformgroup>
            </textbox>
        </textbox>
        <radiobutton content="Savings Account" horizontalalignment="Left" margin="242,143,0,0" verticalalignment="Top" x:name="rbtnSavingsAc">
        <radiobutton content="Current Account" horizontalalignment="Left" margin="381,145,0,0" verticalalignment="Top" x:name="rbtnCurrentAc">
        <radiobutton content="Credit Card" horizontalalignment="Left" margin="243,174,0,0" verticalalignment="Top" x:name="rbtnCreditCard">
        <radiobutton content="Other" horizontalalignment="Left" margin="383,175,0,0" verticalalignment="Top" x:name="rbtnOther">
        <textbox horizontalalignment="Left" margin="242,210,0,0" rendertransformorigin="0.5,0.5" textwrapping="Wrap" verticalalignment="Top" width="192" x:name="txtBalance">
            <textbox .rendertransform=".rendertransform">
                <transformgroup>
                    <scaletransform>
                    <skewtransform>
                    <rotatetransform angle="-3240.009">
                    <translatetransform>
                </translatetransform></rotatetransform></skewtransform></scaletransform></transformgroup>
            </textbox>
        </textbox>
        <button click="btnSave_Click" content="Save" height="23" horizontalalignment="Left" margin="240,269,0,0" rendertransformorigin="0.5,0.5" verticalalignment="Top" width="63" x:name="btnSave">
            </button><button .rendertransform=".rendertransform">
                <transformgroup>
                    <scaletransform scalex="1" scaley="1">
                    <skewtransform anglex="0" angley="0">
                    <rotatetransform angle="-14039.799">
                    <translatetransform>
                </translatetransform></rotatetransform></skewtransform></scaletransform></transformgroup>
            </button>
       

        <datagrid background="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}" height="144" margin="0,318,0,0" mousedoubleclick="BanksetupGrid_MouseDoubleClick" verticalalignment="Top" x:name="BanksetupGrid">
     
    </datagrid></radiobutton></radiobutton></radiobutton></radiobutton></label></label></label></grid>
</window>
Xaml.Cs Code :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;

namespace MoneyWizard
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
       
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\WPFDatabase.accdb");

        public MainWindow()
        {
            InitializeComponent()
            Bind();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            con.Open();
            OleDbCommand cmd = new OleDbCommand("BankTableInsert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@BankName", cmbBankName.SelectedIndex);
            cmd.Parameters.AddWithValue("@AccountNo", txtAcNo.Text);
            if (rbtnSavingsAc.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnSavingsAc.Content);
            }
            else if (rbtnCurrentAc.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnCurrentAc.Content);
            }
            else if (rbtnCreditCard.IsChecked.Value)
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnCreditCard.Content);
            }
            else
            {
                cmd.Parameters.AddWithValue("@AccountType", rbtnOther.Content);
            }


            cmd.Parameters.AddWithValue("@Balance", txtBalance.Text);
            cmd.Parameters.AddWithValue("@Date", System.DateTime.Now.ToShortDateString());

           int result = cmd.ExecuteNonQuery();
           con.Close();
            if (result > 0)
            {
                MessageBox.Show("Record inserted successfully");
            }
            else
            {
                MessageBox.Show("Error occured, please try again", "Alert");
            }
            Bind();
        }

        private void Bind()
        {

            con.Open();
            OleDbDataAdapter da = new OleDbDataAdapter("select * from BankTable”, con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            BanksetupGrid.ItemsSource = dt.DefaultView;
            con.Close();
        }
OutPut :


how to bind or display images from folder to datalist using asp.net or how to insert images into folder and display images from folder to datalist using asp.net


how to bind or display images from folder to datalist using asp.net or how to insert images into folder and display images from folder to datalist using asp.net

Introduction

Here I will explain how insert images into folder and how to bind the images to datalist using asp.net.

Description:

In previous post I explained clearly how to bind images from folder to gridview . Now I will explain how to save images into folder and how we can bind that images to datalist using asp.net. It’s very easy to store images in folder and binding that images to datalist. For that first create one new website after that right click on that website select New Folder give name as Images because here I am using same name if you want to use another name you need to change the name in code also after completion of adding Images folder to your website Design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Images to Datalist from folder</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" onclick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5">
<ItemTemplate>
<asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>
After that add using System.IO and using System.Collections namespaces and write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();

}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
fileupload1.SaveAs(Server.MapPath("Images/" + filename));
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}
}
Demo


Asp.net Create/generate thumbnails from images


Asp.net Create/generate thumbnails from images

Introduction

Here I will explain how to generate thumbnails dynamically from uploaded images and how to bind thumbnails to datalist using asp.net.

Description:

In previous post I explained clearly how to bind images from folder to datalist . Now I will explain how to generate thumbnails from uploaded images and how to bind those thumbnails to datalist using asp.net. In website development sometimes we get requirement like generating thumbnails from images without losing quality of image and it’s same like original image. For that first create one new website after that right click on that website select New Folder give name as Images because here I am using same name if you want to use another name you need to change the name in code also. After completion of adding Images folder to your website Design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Generate a Thumbnails from Uploaded Image</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" onclick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>' NavigateUrl='<%# Bind("Name", "~/Images/{0}") %>' runat="server"/>
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</div>
</form>
</body>
</html>
After that add following namespaces in code behind

using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
After completion of adding namespaces write the following code


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();

}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.07, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}
}
DEMO:

Read the data from Excel Sheet and bind it to Gridview in asp.net


 Read the data from Excel Sheet and bind it to Gridview in asp.net


Here i will explain how to read the data from Excel sheet and bind that data to gridview in asp.net

1) First take one upload control, one button and one gridview like this


  2) Design Aspx page like this you just copy and paste the below aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Reading Excel data</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <p>
 <asp:Label ID="Label1" runat="server">SpreadSheetContents:</asp:Label></p>
 <asp:FileUpload ID="fileupload" runat="server" /><br />
 <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
 <asp:DataGrid ID="DataGrid1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
 <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
 <AlternatingItemStyle BackColor="White" />
 <ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />
 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 </asp:DataGrid>
</div>
 </form>
</body>
</html>

3) In button click you should write the following code



protected void btnSubmit_Click(object sender, EventArgs e)
    {
string path = fileupload.PostedFile.FileName;
 string strmail = string.Empty;
 string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
 OleDbConnection objConn = new OleDbConnection(connectionString);
 objConn.Open();
 String strConString = "SELECT UserName,EmailId FROM [Sheet1$]";
 //where date = CDate('" + DateTime.Today.ToShortDateString() + "')";
 OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
 // Create new OleDbDataAdapter that is used to build a DataSet
 // based on the preceding SQL SELECT statement.
 OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
 // Pass the Select command to the adapter.
 objAdapter1.SelectCommand = objCmdSelect;
 // Create new DataSet to hold information from the worksheet.
 DataSet objDataset1 = new DataSet();
 // Fill the DataSet with the information from the worksheet.
 objAdapter1.Fill(objDataset1, "ExcelData");
 DataGrid1.DataSource = objDataset1;
 DataGrid1.DataBind();
   // Clean up objects.
   objConn.Close();
}


4) For accessing oledb conncetion you should enter name spaces
using System.Data.SqlClient;
using System.Data.OleDb;

After Completion of  all the steps you should press F5
and upload the excel sheet by using upload control and press submit button after completion of this you will find output like this


  Here one important point is you need format your excel sheet like this

 
String strConString = "SELECT UserName,EmailId FROM [Sheet1$]";
Here in string i have written query to get the data from UserName,EmailId from Sheet1 thats why i have format excel sheet with First column UserName  Second Column with EmailId and i have given difault name Sheet1 for that Sheet.if you want columns with anthor names you should change the query also. In query you should write the Columns whatever you have enter in Excel Sheet

i think it help you

ajax with json displaydata to gridview


 Bind data to gridview with JQuery or JSON in asp.net

Introduction:

In this article I will explain how to bind data to gridview and display it on our aspx page using JQuery or JSON in asp.net.

Description:

In previous article I explained JQuery UI AutoComplete textbox with database and call asp.net pagemethods in JQuery. Now I am using those concepts to explain how to bind data to gridview using JQuery/JSON and display it on aspx page in asp.net.
To implement this concept first we need to design table in database give name as UserInformation to save user details in database.


Display sum of columns total in gridview footer in asp.net


 Display sum of columns total in gridview footer in asp.net

Introduction:

In this article I will explain how to display the sum of total of columns in gridview footer   using asp.net.

Description:

I have a one gridview with multiple rows and columns and for that gridview paging also has enabled now my requirement I need to display sum of all the columns (Total) in gridview footer for that I have used gridview row databound condition this functionality will work for paging enabled gridview also. Before proceed to functionality first we need to design one table in database and give name EmployeeSalary


ColumnName

DataType
EmpID

Int(set identity property=true)
EmpName

varchar(50)
Location

varchar(50)
Amount

varchar(50)
After completion table creation enter some dummy and design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show gridview Rows Total in </title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmp" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold ="true" DataKeyNames="EmpID" runat="server" ShowFooter="true" AllowPaging="true" PageSize="5" AutoGenerateColumns="false" DataSourceID ="sqldsEmp" onrowdatabound="gvEmp_RowDataBound">
<FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" />
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="Emp ID" />
<asp:BoundField DataField="EmpName" HeaderText="Emp Name" />
<asp:TemplateField  HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltxttotal" runat="server" Text="Total Amount"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Eval("Amount") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsEmp" runat="server" SelectCommand="select * from EmployeeSalary" ConnectionString="<%$ ConnectionStrings:dbconnection %>">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

After completion of aspx page write the following code in codebehind

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >


Demo


Maintaining State of CheckBoxes While Paging in a GridView Control


Maintaining State of CheckBoxes While Paging in a GridView Control

Introduction:
In this article I will explain how to maintain state of selected checkboxes during paging in gridview using asp.net
Description:

I have one gridview with checkboxes and it contains lot of data for that reason I applied paging for gridview and displaying 8 records per page. After apply the paging in gridview if I select checkboxes in first page and moving to another page and select some checkboxes in second page after that if I come back I am unable to see the previous selected values. At that time I know one new thing that is gridview won’t maintain the state of controls during postback for that reason we need write some code to maintain the previous selected values in gridview. Before seeing the code implemention first Design your aspx page like this



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Maintain State Checkboxes during paging</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvdetails" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" onpageindexchanging="gvdetails_PageIndexChanging" PageSize="8" DataKeyNames="UserId">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After completion of aspx page design add the following references in code behind


using System.Collections;
using System.Data;
using System.Data.SqlClient;



After completion of adding reference write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridData();
}
}
//This method is used to bind the gridview
protected void BindGridData()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("select * from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SaveCheckedValues();
gvdetails.PageIndex = e.NewPageIndex;
BindGridData();
PopulateCheckedValues();
}
//This method is used to populate the saved checkbox values
private void PopulateCheckedValues()
{
ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (userdetails != null && userdetails.Count > 0)
{
foreach (GridViewRow gvrow in gvdetails.Rows)
{
int index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
if (userdetails.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
//This method is used to save the checkedstate of values
private void SaveCheckedValues()
{
ArrayList userdetails = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in gvdetails.Rows)
{
index = (int)gvdetails.DataKeys[gvrow.RowIndex].Value;
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;

// Check in the Session
if (Session["CHECKED_ITEMS"] != null)
userdetails = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!userdetails.Contains(index))
userdetails.Add(index);
}
else
userdetails.Remove(index);
}
if (userdetails != null && userdetails.Count > 0)
Session["CHECKED_ITEMS"] = userdetails;
}

If you observe above code I written one method to bind our gridview and written two more methods those are SaveCheckedValues and PopulateCheckedValues these two methods are used to maintain the state of selected checkbox values during paging in gridview. In SaveCheckedValues method I used Session variable to maintain the selected checkbox values after that by using this saved session values I am populating the checkbox state in PopulateCheckedValues method.

Demo



Gridview checkbox validation using javascript


 Gridview checkbox validation using javascript

Introduction

Hi here I will explain how to check the checked status of checkboxes in gridview using JavaScript

Description

I have a one gridview with checkboxes and one button if user clicks on button I need to raise validation if user doesn’t checked at least one checkbox in gridview for that I have written one JavaScript function to check whether checkboxes selected in gridview or not.

For that write the following code in aspx page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Check all checkboxes if Header checkbox checks</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
<script type="text/javascript" language="javascript">
function validateCheckBoxes() {
var isValid = false;
var gridView = document.getElementById('<%= gvcheckbox.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
if (inputs != null) {
if (inputs[0].type == "checkbox") {
if (inputs[0].checked) {
isValid = true;
return true;
}
}
}
}
alert("Please select atleast one checkbox");
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvcheckbox" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server"/>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:BoundField HeaderText = "UserName" DataField="UserName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField HeaderText="FirstName" DataField="FirstName" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField HeaderText="LastName" DataField="LastName" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
<asp:button runat="server" Text="Submit" OnClientClick="javascript:validateCheckBoxes()"/>
</div>
</form>
</body>
</html>

In code behind bind gridview with some data and check it will work for you

Demo



Delete multiple asp.net gridview rows with checkbox selection and with confirmation


Delete multiple asp.net gridview rows with checkbox selection and with confirmation

Introduction:

In this article I will explain how to delete multiple rows in gridview with checkbox selection and with confirmation message using asp.net.

Description:

I have one gridvew that contains multiple rows with checkboxes now my requirement is to delete rows in gridview based on checkbox selection.


First design the table in database and give name UserInformation
ColumnName

DataType
UserId

Int(set identity property=true)
UserName

varchar(50)
FirstName

varchar(50)
LastName

varchar(50)
Location

varchar(50)
After completion table creation enter some dummy and design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Delete Rows in Gridview with Checkbox</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
<script type="text/javascript">
function Confirmationbox() {
var result = confirm('Are you sure you want to delete selected User(s)?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserDetails" runat="server" DataSourceID="objUsers"
DataKeyNames="UserId" CssClass="Gridview" AutoGenerateColumns="false"
HeaderStyle-BackColor="#61A6F8" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="objUsers" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"
DeleteCommand="delete from UserInformation where UserId=@UserId" >
<DeleteParameters>
<asp:Parameter Name="UserId" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />
</form>
</body>
</html>

After completion of aspx page write the following code in codebehind


protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Attributes.Add("onclick", "javascript:return Confirmationbox()");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Loop through all the rows in gridview
foreach(GridViewRow gvrow in gvUserDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkdelete");
//Condition to check checkbox selected or not
if(chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
objUsers.DeleteParameters["UserId"].DefaultValue = usrid.ToString();
objUsers.Delete();
}
}
After that set your database connection in web.config like this because we are using this connection in our sqldatasource to get the data from database


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Demo