RSS

Category Archives: Vb.Net

vb.net related article

devexpress multiple gridview export to excel in Single File winforms


After two much searching of this solution to export multiple gridview data to single Excel file with separate Sheet of Excel.

Then i find this solution which resolve my problem. this is 100% tested and use in my project . after that i share with you in both language c# and vb.net.

 

 Solution :: Vb.Net

Imports DevExpress.XtraPrinting
Imports DevExpress.XtraPrintingLinks

 

Public Sub MultiFileExportToExcel()

Using saveDialog = New SaveFileDialog()
saveDialog.Filter = “Excel (.xlsx)|*.xlsx”
If saveDialog.ShowDialog() = DialogResult.OK Then
Dim printingSystem = New PrintingSystemBase()
Dim compositeLink = New CompositeLinkBase()
compositeLink.PrintingSystemBase = printingSystem

Dim link1 = New PrintableComponentLinkBase()
link1.Component = grid1
Dim link2 = New PrintableComponentLinkBase()
link2.Component = grid2

compositeLink.Links.Add(link1)
compositeLink.Links.Add(link2)

Dim options = New XlsxExportOptions()
options.ExportMode = XlsxExportMode.SingleFilePageByPage

compositeLink.CreatePageForEachLink()
compositeLink.ExportToXlsx(saveDialog.FileName, options)
End If
End Using
End Sub

 

Solution ::  C#

using DevExpress.XtraPrinting
using DevExpress.XtraPrintingLinks

public void exportToExcel()
{
using (var saveDialog = new SaveFileDialog())
{
saveDialog.Filter = “Excel (.xlsx)|*.xlsx”;
if (saveDialog.ShowDialog() == DialogResult.OK)
{
var printingSystem = new PrintingSystemBase();
var compositeLink = new CompositeLinkBase();
compositeLink.PrintingSystemBase = printingSystem;

var link1 = new PrintableComponentLinkBase();
link1.Component = grid1;
var link2 = new PrintableComponentLinkBase();
link2.Component = grid2;

compositeLink.Links.Add(link1);
compositeLink.Links.Add(link2);

var options = new XlsxExportOptions();
options.ExportMode = XlsxExportMode.SingleFilePageByPage;

compositeLink.CreatePageForEachLink();
compositeLink.ExportToXlsx(saveDialog.FileName, options);
}
}
}

 

Reference url;

https://www.devexpress.com/Support/Center/Question/Details/A2730

Advertisements
 
Leave a comment

Posted by on April 22, 2015 in Vb.Net, WinForm

 

Tags: ,

Deleting older files after a specified number of days using VB.NET


If You want to Temp or your specific Export file History maintain folder to delete file after some days then this function resolve your problem.

Calling Way:

First Way : 

Dim DeleteInfo As Long()

DeleteInfo = DeleteFilesXDaysOld("c:\temp\", "*.*", 60)

Console.Writeline(DeleteInfo(0) & " file(s) deleted.")
Console.Writeline("Freeing " & DeleteInfo(1) & " bytes.")


Second Way:

Imports System.IO

 Dim DeleteInfo As Long()
 If My.Computer.FileSystem.DirectoryExists(Path.GetTempPath & "\Export\Invoice") = True Then
 DeleteInfo = DeleteFilesXDaysOld(Path.GetTempPath & "\Export\Invoice", "*.*", 2)
 End If

Check Directory Exist or Not in Vb.Net else create

Dim GLFilePath as string = Path.GetTempPath & "\Export\Invoice"

 If My.Computer.FileSystem.DirectoryExists(Path.GetTempPath & "\Export\Invoice") = False Then
 My.Computer.FileSystem.CreateDirectory(Path.GetTempPath & "\Export\Invoice")
 End If

Function Delete Files:

Private Function DeleteFilesXDaysOld( _ ByVal Path As String, _ Optional ByVal Pattern As String = "*.*", _ Optional ByVal Days As Integer = 365) As Long() ' ReturnValues is an array which holds 2 values ' The first being the count of files deleted ' The second being the amount of space freed Dim ReturnValues = New Long() {0,0} Dim File As String Dim FileInfo As System.IO.FileInfo Dim Files() As String = _ System.IO.Directory.GetFiles(Path, Pattern) Try For Each File In Files FileInfo = New System.IO.FileInfo(File) If FileInfo.LastWriteTime < _ Today.AddDays(0 - Days) Then ReturnValues(0) += 1 ReturnValues(1) += FileInfo.Length() FileInfo.Delete() End If Next Return ReturnValues Catch exn As Exception MsgBox(exn.ToString, _ MsgBoxStyle.Critical Or _ MsgBoxStyle.OkOnly Or _ MsgBoxStyle.SystemModal, _ "Error") Return ReturnValues End Try End Function

 
1 Comment

Posted by on February 15, 2015 in Vb.Net

 

Tags: , , , , ,

Convert Simple Number to Arabic Number.


You can use this code both Web & Desktop Application.

Code 1: the HTML code:

<form id=”form1″ runat=”server”>

<asp:TextBox ID=”txtNumber” runat=”server”></asp:TextBox>

<br />

<asp:Label ID=”lblmsg” runat=”server”></asp:Label>

<br />

<asp:Button ID=”btnConvert” runat=”server” Text=”Convert to Arabic” />

</form>

 

Code 2: Code Behind

 

Protected Sub btnConvert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

 

‘Call Function

Me.lblmsg.Text = “Arabic Number : <b>” & TranslateNumerals(Me.txtNumber.Text.Trim) & “</b>”

End Sub

 

 

Public Shared Function TranslateNumerals(ByVal sIn As String) As String

 

Dim enc As New System.Text.UTF8Encoding

 

Dim utf8Decoder As System.Text.Decoder

 

utf8Decoder = enc.GetDecoder

 

Dim sTranslated = New System.Text.StringBuilder

 

Dim cTransChar(1) As Char

 

Dim bytes() As Byte = {217, 160}

 

‘ Start Converting characters into Arabic mode.

 

Dim aChars() As Char = sIn.ToCharArray

 

For Each c As Char In aChars

 

If Char.IsDigit(c) Then

 

bytes(1) = 160 + CInt(Char.GetNumericValue(c))

 

utf8Decoder.GetChars(bytes, 0, 2, cTransChar, 0)

 

sTranslated.Append(cTransChar(0))

 

Else

 

sTranslated.Append(c)

 

End If

 

Next

 

TranslateNumerals = sTranslated.ToString

 

End Function

 

 

After you run the page, enter some English number and then click “Convert to Arabic” button to display the entered number in Arabic number mode.

picArabicNo2

 
Leave a comment

Posted by on October 2, 2014 in Vb.Net

 

Tags: ,

Encryption/Decryption Function in .NET


 

C#

 

public string Encrypt(string str)
    {
        string EncrptKey = “2013;[pnuLIT)X”;
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

 public string Decrypt(string str)
    {
        str = str.Replace(” “, “+”);
        string DecryptKey = “2013;[pnuLIT)Y”;
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byte[] inputByteArray = new byte[str.Length];
        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(str.Replace(” “, “+”));
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }

 

VB.Net

Public Function Encrypt(str As String) As String
Dim EncrptKey As String = “2013;[pnuLIT)X”
Dim byKey As Byte() = {}
Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
205, 239}
byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(str)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function

 
Public Function Decrypt(str As String) As String
str = str.Replace(” “, “+”)
Dim DecryptKey As String = “2013;[pnuLIT)Y”
Dim byKey As Byte() = {}
Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
205, 239}
Dim inputByteArray As Byte() = New Byte(str.Length – 1) {}

byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(str.Replace(” “, “+”))
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
End Function

 

 
1 Comment

Posted by on November 22, 2013 in ASP Dot Net C#, Vb.Net

 

Tags: , , ,

U.S.A Postal Address Validation


To use USA Address validation

download DLL file and Code

https://skydrive.live.com/?cid=fcca6a631a7ce903

 web.config

<appSettings>

<!– set the “proxy” key value to the null string to turn off proxy –>

<!– e.g. 10.10.201.3:8080 –>

<add key=”proxy” value=””/>

<add key=”proxyUserName” value=””/>

<add key=”proxyPassword” value=””/>

</appSettings>

AddressValidator.aspx

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title>Address Verification For USA</title>

<script type=”text/javascript”>

function YahooWindow() {

var street = document.getElementById(‘<%=txtAddress.ClientID %>’).value;

var city = document.getElementById(‘<%=txtCity1.ClientID %>’).value;

var e = document.getElementById(‘<%=ddlState.ClientID%>’);

//For ModelWindow then uncomment below code

//            $(“#Address1″).fancybox({

//                ‘width’: ‘55%’,

//                ‘height’: ‘30%’,

//                ‘autoScale’: false,

//                ‘transitionIn’: ‘none’,

//                ‘transitionOut’: ‘none’,

//                ‘type’: ‘iframe’

//            });

var strV = e.options[e.selectedIndex].text;

//alert(city);

document.getElementById(‘Address2’).href = ‘AddressVerification.aspx?street=’ + street + ‘&city=’ + city + ‘&state=’ + strV + ”

//yahoowin = dhtmlmodal.open(‘yahoo’, ‘iframe’, ‘AddressVerification.aspx?street=’ + street + ‘&city=’ + city + ‘&state=’ + strV + ”, ‘Address Verification’, ‘width=400px,height=350px,center=1’);

//             $(“#Address1″).click();

//             return false;

}

</script>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

<table>

<tr>

<td class=”sub02″ width=”180px”>

Address:

</td>

<td>

<asp:TextBox runat=”server” ID=”txtAddress” CssClass=”input” />

<a href=”#” id=”Address2″ onclick=”return YahooWindow();”>[Verify Address] </a><a

href=”#” id=”Address1″></a>

</td>

</tr>

<tr>

<td class=”sub02″ width=”180px”>

City:

</td>

<td>

<asp:TextBox runat=”server” ID=”txtCity1″ CssClass=”input” />

</td>

</tr>

<tr>

<td class=”sub02″ width=”180px”>

State:

</td>

<td>

<asp:DropDownList runat=”server” ID=”ddlState” CssClass=”input”>

<asp:ListItem>–Select State–</asp:ListItem>

<asp:ListItem>AK</asp:ListItem>

<asp:ListItem>AL</asp:ListItem>

<asp:ListItem>AR</asp:ListItem>

<asp:ListItem>AZ</asp:ListItem>

<asp:ListItem>CA</asp:ListItem>

<asp:ListItem>CO</asp:ListItem>

<asp:ListItem>CT</asp:ListItem>

<asp:ListItem>DC</asp:ListItem>

<asp:ListItem>DE</asp:ListItem>

<asp:ListItem>FL</asp:ListItem>

<asp:ListItem>GA</asp:ListItem>

<asp:ListItem>HI</asp:ListItem>

<asp:ListItem>IA</asp:ListItem>

<asp:ListItem>ID</asp:ListItem>

<asp:ListItem>IL</asp:ListItem>

<asp:ListItem>IN</asp:ListItem>

<asp:ListItem>KS</asp:ListItem>

<asp:ListItem>KY</asp:ListItem>

<asp:ListItem>LA</asp:ListItem>

<asp:ListItem>MA</asp:ListItem>

<asp:ListItem>MD</asp:ListItem>

<asp:ListItem>ME</asp:ListItem>

<asp:ListItem>MI</asp:ListItem>

<asp:ListItem>MN</asp:ListItem>

<asp:ListItem>MO</asp:ListItem>

<asp:ListItem>MS</asp:ListItem>

<asp:ListItem>MT</asp:ListItem>

<asp:ListItem>NC</asp:ListItem>

<asp:ListItem>ND</asp:ListItem>

<asp:ListItem>NE</asp:ListItem>

<asp:ListItem>NH</asp:ListItem>

<asp:ListItem>NJ</asp:ListItem>

<asp:ListItem>NM</asp:ListItem>

<asp:ListItem>NV</asp:ListItem>

<asp:ListItem>NY</asp:ListItem>

<asp:ListItem>OH</asp:ListItem>

<asp:ListItem>OK</asp:ListItem>

<asp:ListItem>OR</asp:ListItem>

<asp:ListItem>PA</asp:ListItem>

<asp:ListItem>RI</asp:ListItem>

<asp:ListItem>SC</asp:ListItem>

<asp:ListItem>SD</asp:ListItem>

<asp:ListItem>TN</asp:ListItem>

<asp:ListItem>TX</asp:ListItem>

<asp:ListItem>UT</asp:ListItem>

<asp:ListItem>VA</asp:ListItem>

<asp:ListItem>VT</asp:ListItem>

<asp:ListItem>WA</asp:ListItem>

<asp:ListItem>WI</asp:ListItem>

<asp:ListItem>WV</asp:ListItem>

<asp:ListItem>WY</asp:ListItem>

</asp:DropDownList>

</td>

</tr>

<tr>

<td class=”sub02″ width=”180px”>

Zip:

</td>

<td>

<asp:TextBox runat=”server” ID=”txtZipCode” CssClass=”input” />

</td>

</tr>

</table>

</div>

</form>

</body>

</html>

AddressVerification.aspx

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title></title>

<style type=”text/css”>

body{ margin:0;

padding:0;

font-family:Arial, helventica, Verdana;

font-size:11px;

}

</style>

</head>

<body>

<form id=”form1″ runat=”server”>

<div  style=”text-align: left; vertical-align: middle;”>

<asp:Image runat=”server” id=”imgNo” ImageAlign=”AbsMiddle” ImageUrl=”~/images/no.jpg”></asp:Image>

<asp:Image runat=”server” id=”imgYes” ImageAlign=”AbsMiddle” ImageUrl=”~/images/yes.jpg”></asp:Image>

<asp:Label runat=”server” id=”lblVerification”></asp:Label>

</div>

<div  style=”text-align: left; padding-left:75px;”>

<asp:RadioButton runat=”server” id=”rdo1″ Text=”Give me some address suggestions” GroupName=”rdosug” AutoPostBack=”true”></asp:RadioButton><br />

<asp:RadioButton runat=”server” id=”rdo2″ Text=”The address I entered is correct” GroupName=”rdosug” AutoPostBack=”true”></asp:RadioButton> <br />

<asp:RadioButton runat=”server” id=”rdo3″ Text=”I will make my address corrections  ” GroupName=”rdosug” AutoPostBack=”true”></asp:RadioButton>

</div>

</form>

</body>

</html>

 
Leave a comment

Posted by on June 30, 2011 in Vb.Net

 

Tags: , ,

How To Display A Loading Image When Gridview Data Loading Is In Progress


ClientSite

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Loading.aspx.cs” Inherits=”Loading” %>

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head runat=”server”>

<title></title>

<link href=”style/ModelExtender.css” rel=”stylesheet” type=”text/css” />

</head>

<body  >

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

</asp:ScriptManager>

<div style=”margin-left:255px;margin-top:76px”>

<asp:UpdateProgress ID=”UpdateProgress2″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel2″>

<ProgressTemplate>

<div id=”progressBackgroundFilter”></div>

<div id=”processMessage”></div>

</ProgressTemplate>

</asp:UpdateProgress>

<asp:UpdatePanel ID=”UpdatePanel2″ runat=”server” UpdateMode=”Conditional”>

<ContentTemplate>

<br />

<asp:Button ID=”btnLoad” runat=”server”

Text=”Load Grid” onclick=”btnLoad_Click” ForeColor=”Red” />

<br />  <br />

<asp:GridView ID=”GridView1″ runat=”server” CellPadding=”4″ ForeColor=”#333333″

GridLines=”None” AutoGenerateColumns=”false” AllowPaging=”True”

PageSize=”5″>

<AlternatingRowStyle BackColor=”White” />

<Columns>

<asp:BoundField DataField=”DocumentID” HeaderText=”DocumentID ” />

<asp:BoundField DataField=”Title” HeaderText=”Title  ” />

<asp:BoundField DataField=”displayTitle” HeaderText=”displayTitle ” />

<asp:BoundField DataField=”friendlyUrl” HeaderText=”friendlyUrl ” />

</Columns>

<EditRowStyle BackColor=”#2461BF” />

<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />

<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />

<RowStyle BackColor=”#EFF3FB” />

<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />

<SortedAscendingCellStyle BackColor=”#F5F7FB” />

<SortedAscendingHeaderStyle BackColor=”#6D95E1″ />

<SortedDescendingCellStyle BackColor=”#E9EBEF” />

<SortedDescendingHeaderStyle BackColor=”#4870BE” />

</asp:GridView>

</ContentTemplate>

</asp:UpdatePanel>

</div>

</form>

</body>

</html>

ServerSide

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class Loading : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

//System.Threading.Thread.Sleep(5000);

}

}

public static DataSet Events_getAll(string qry)

{

sqlhelper data_manager = new sqlhelper();

Hashtable ht_params = null;

DataSet dt = null;

try

{

ht_params = new Hashtable();

dt = data_manager.SQLDataSet(qry);

return dt;

}

catch (Exception ex)

{

throw ex;

}

finally

{

ht_params = null;

data_manager = null;

}

}

private void BindGridViewView()

{

string qry = “select * from documents where  siteid=76”;

GridView1.DataSource = Events_getAll(qry);

GridView1.DataBind();

}

protected void btnLoad_Click(object sender, EventArgs e)

{

BindGridViewView();

}

}

 
1 Comment

Posted by on June 10, 2011 in Vb.Net

 

Tags: , , , , ,

Custom Gridview Paging and Sorting with Vb.net (Styling)


Asp File

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
<ContentTemplate>

<asp:GridView ID=”grdList” runat=”server” CellPadding=”2″ CellSpacing=”0″ BorderWidth=”0px”
AutoGenerateColumns=”False” GridLines=”None”
OnPageIndexChanging=”grdList_PageIndexChanging”  Width=”100%”
CssClass=”listing-table”  AllowSorting=”true” AllowPaging=”true”
PageSize=”3″   ShowFooter=”True” onrowcreated=”grdList_RowCreated” >
<Columns>
<asp:BoundField DataField=”Title” HeaderText=”Name” SortExpression=”Name” />
<asp:BoundField DataField=”Class” HeaderText=”Class” SortExpression=”Class” />
<asp:BoundField DataField=”RollNo” HeaderText=”RollNo” SortExpression=”RollNo”  />

</Columns>
<PagerTemplate>
<div>
<div id=”pagn”>
Goto Page
<asp:DropDownList ID=”ddlPageSelector” runat=”server” AutoPostBack=”true”>
</asp:DropDownList>
of
<%=grdList.PageCount%>

<asp:Label ID=”lblNumber” runat=”server”></asp:Label>
<span>
<asp:Button Text=”First” CommandName=”Page” CommandArgument=”First” runat=”server”
ID=”btnFirst” />
<asp:Button Text=”Previous” CommandName=”Page” CommandArgument=”Prev” runat=”server”
ID=”btnPrevious” />
</span>
<%– <span>|</span>–%>
<%–<span>|</span>–%>
<span>
<asp:Button Text=”Next” CommandName=”Page” CommandArgument=”Next” runat=”server”
ID=”btnNext” />
<asp:Button Text=”Last” CommandName=”Page” CommandArgument=”Last” runat=”server”
ID=”btnLast” />
<div style=”float: right;padding-right:15px”>
Record Per Page:
<asp:TextBox ID=”txtPageSize” runat=”server” Width=”25px” EnableViewState=”true”></asp:TextBox>
<asp:LinkButton ID=”lnkSavePageSize” runat=”server” ValidationGroup=”grpList” OnClick=”lnkSavePageSize_Click”><strong>Save</strong></asp:LinkButton>

</div>
</span>
</div>
</div>

<asp:CompareValidator ValidationGroup=”grpList” Display=”None” ID=”CompareValidator1″
ControlToValidate=”txtPageSize” Type=”Integer” Operator=”DataTypeCheck” runat=”server”
ErrorMessage=”Enter numeric value.”></asp:CompareValidator>
<asp:ValidationSummary ValidationGroup=”grpList” ShowSummary=”false” ShowMessageBox=”true”
ID=”ValidationSummary1″ runat=”server” />
</PagerTemplate>
</asp:GridView>

</ContentTemplate>
</asp:UpdatePanel>

Code Behid

private void BindData()
{
grdList.DataSource = (Pass Dataset or datatable Here)
grdList.DataBind();
}

protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdList.PageIndex = e.NewPageIndex;
BindData();

}
protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
{

string sortExpression = e.SortExpression;

ViewState[“SortExpression”] = sortExpression;

if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, “DESC”);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, “ASC”);
}

}

private SortDirection GridViewSortDirection
{

get
{

if (ViewState[“sortDirection”] == null)

ViewState[“sortDirection”] = SortDirection.Ascending;

return (SortDirection)ViewState[“sortDirection”];

}

set { ViewState[“sortDirection”] = value; }

}

private void SortGridView(string sortExpression, string direction)
{

DataTable dataTable = new DataTable();
dataTable = getData();
DataView dv = new DataView();
dv = dataTable.DefaultView;
dv.Sort = sortExpression + ” ” + direction;

grdList.DataSource = dv;
grdList.DataBind();

}

protected void grdList_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(grdList, e.Row, this);
}
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page)
{

int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
Button btnFirst = (Button)gvPagerRow.FindControl(“btnFirst”);
Button btnPrevious = (Button)gvPagerRow.FindControl(“btnPrevious”);
Button btnNext = (Button)gvPagerRow.FindControl(“btnNext”);
Button btnLast = (Button)gvPagerRow.FindControl(“btnLast”);
TextBox txtPageSize = (TextBox)gvPagerRow.FindControl(“txtPageSize”);
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount – 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(“ddlPageSelector”);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
txtPageSize.Text = gridView.PageSize.ToString();
//Anonymous method (see another way to do this at the bottom)
ddlPageSelector.SelectedIndexChanged += delegate
{
grdList.PageIndex = ddlPageSelector.SelectedIndex;
BindData();
};
//for vb.net( VB.net 2.0 does not support anonymous methods)

//protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
//{
//GridView1.PageIndex = ((DropDownList)sender).SelectedIndex;
//GridView1.DataBind();
//}
}

protected void lnkSavePageSize_Click(object sender, EventArgs e)
{
GridViewRow pagerRow = grdList.BottomPagerRow;
TextBox temp1 = (TextBox)pagerRow.FindControl(“txtPageSize”);
if (temp1.Text != “”)
{
grdList.PageSize = Convert.ToInt32(temp1.Text);
}
}

CSS for Paging

/*Amazon*/
div.header {
border-top: 1px solid #d0eaf8;
border-bottom: 1px solid #d0eaf8;
width: 100%;
margin: 4px 0;
}

div.resultCount {
width: 29%;
}

div.pagn {
text-align: left;
width: 100%;
}

div.pagnBtm {
text-align: center;
width: 100%;
}

div.pagn .pagnCur, div.pagnBtm .pagnCur
{
font-weight: bold;
padding: 0 5px;
}

div.pagn .pagnDisabled, div.pagnBtm .pagnDisabled {
color: #999;
padding: 0px 5px;
white-space: nowrap;
}

div.pagn .pagnMore, div.pagn .pagnSep, div.pagnBtm .pagnMore, div.pagnBtm div.pagnSep {
padding: 0 2px;
}

div.pagn .pagnLead, div.pagnBtm .pagnLead {
font-weight: bold;
padding: 0 5px 0 2px;
}

div.pagn input, div.pagn input:visited, div.pagnBtm input, div.pagnBtm input:visited {
text-decoration: none;
padding: 6px;
color: #055d90;
white-space: nowrap;
}

div.pagn input:hover, div.pagn input:active, div.pagnBtm input:hover, div.pagnBtm input:active
{
text-decoration: none;
padding: 6px;
color:#050;
white-space: nowrap;

}

div.headerPaging {
background: url(“../images/tile-blue-bg._V45465059_.gif”) repeat-x;
}

 

Image for CSS

 
1 Comment

Posted by on June 4, 2011 in Gridview, Vb.Net

 

Tags: ,