Thursday, August 6, 2009

Export Grid to Excel

Export to Excel

In this article we are going to read and understand how in a web application we can export a grid data in the excel file. As many times in real time programming we generate reports in the grid format to display to the user.

For example

1 .The list of commodities purchased this month

2. Reports of SMS Sent.

3. Reports of invites. etc.and user might want to save this list for the future use. In Excel format then we need to export this grid to the excel.

Prerequisites:

1. To view an Excel workbook file's contents, you must have installed Microsoft Excel (alone or with MS-Office) on your system.

2. Microsoft Visual Studio (VS) must be installed on the (I haven't tested it on the Prior versions)

Let's start with creating an application in VS2008 (You can even go for VS2005 or VS2010)

Following the steps to we are going to follow.

  1. Create a new project in VS2008 as name it as "ExporttoExcel" in the C# category.
  2. Place a gridview on the default.aspx page and rename it to grdtoexport.
  3. And place a button which will export the grid to excel.
  4. Now lets create a datatable which will bind the grid.

The Code will look like:

protected void Page_Load(object sender, EventArgs e)

{

//creating a table for the grid use namespace System.Data;

DataTable dt = new DataTable ();

//adding columns to the datatale

try

{

dt.Columns.Add("Srno");

dt.Columns.Add("Name");

}

catch { }

//adding values to the datatable

for (int i = 1; i <= 10; i++)

{

DataRow dr = dt.NewRow();

dr[0] = i;

dr[1] = "Meetu Choudhary " + i.ToString();

dt.Rows.Add(dr);

}

//binding databale to the grid

grdtoexport.DataSource = dt;

grdtoexport.DataBind();

}

Writing a ExportToExcel class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Configuration;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;

namespace ExportToExcel

{

/// <summary>

/// Summary description for ExportToExcel

/// </summary>

public class ExportToExcel

{

public ExportToExcel()

{

//

// TODO: Add constructor logic here

//

}

public void ExportGridView(GridView GridView1, String strFileName)

{

PrepareGridViewForExport(GridView1);

//string attachment = "attachment; filename=Contacts.xls";

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.Buffer = true;

HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);

HttpContext.Current.Response.ContentType = "application/ms-excel";

HttpContext.Current.Response.Charset = "";

//System.Web.UI.Page.EnableViewState = false;

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

HttpContext.Current.Response.Write(sw.ToString());

HttpContext.Current.Response.End();

}

private void PrepareGridViewForExport(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(CheckBox))

{

l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

if (gv.Controls[i].HasControls())

{

PrepareGridViewForExport(gv.Controls[i]);

}

}

}

/*Use this commented function in all the pages where the above export function is used

//public override void VerifyRenderingInServerForm(Control control)

//{

//}*/

}

}

Calling the Function to export on button click

protected void btnexport_Click(object sender, EventArgs e)

{

ExportToExcel ex = new ExportToExcel();

ex.ExportGridView(grdtoexport, "Client.xls");

}



You can download the code from here


Regards, Meetu Choudhary
Microsoft MVP-ASP/ASP.NET

MsDnM My Forums My Blog

Monday, August 3, 2009

Progress Bar demo

Hi All,

I am Developing this Application just to help a newbie in the technology and even many of my students have asked me for the application which will demonstrate them how to use a progress bar in C#.net for a windows application. So here is a small application which will solve the purpose.

So Here Is the application and description how to develop the application.

1. Create a New Project in VS 2008 or above as per your convince I have installed VS 2008 so I am using that if you want to use VS 2005 you can even go with that also. For now VS2008


2. Create New Project : Select Windows Forms Application under the Visual C# tab and give the name to the project as prjProgressBar.

3. Now Place The ProgressBar Control and the Button Tool on the form from the tools box as shown in the figure below.

4. Set the following Properties of the progress bar:

  • Minimum =0 (By Default). This value will specify the lower bound for the progress bar.
  • Maximum =500 (Default value is 100). This is the upper bound value of the progress bar when progress is complete.
  • Step= 5 (Default is 10) This value is the value by which the progressbar will increase the current value with the next step when performstep function will be called. (in this case 500/5=100 i.e. in ten steps we will complete the progressbar.)
  • Value =0 (Default is 0) This will set or get the current value of the progressbar.
  • Style is the cosmetic property of the control default is blocks you may change it to marquee or continues. I am not changing it.
  • MarqueeanimationSpeed=100 (default is also 100): this is the speed in milisseconds set for the animation of the progressbar.

Now On the button click event we will start the progress bar and show a message at final step that in how many steps we have completed the progress bar. The code will be:

private void button1_Click(object sender, EventArgs e)
{
int i = 0;
while (progressBar1.Value < progressBar1.Maximum )
{
MessageBox.Show("Step : " + i);
}
}

>Now The above code I have written on the button click so you can write it at any place you needed. Suppose You want that as the data is begin added in the database then you need to perform a step in the database you can do that. But in that case you should set the maximum value of the progressbar to the total no. of records to be inserted and this will be set by the code at the event where you have calculated the total no. of records. with the help of this line.

progressBar1.Maximum=NoRecs;

and the step value should be 1 and when the insertion is completed in the database then use
progressBar1.PerformStep();
line of code there.

The Sample Code is attached.


Thanks and Regards
Meetu Choudhary
MVP || My Blog || MySite || My Forums

Thursday, July 30, 2009

How to use combo box in silverlight

After reading this article we will be able to use a comboobx in a Silverlight application as we are habitual of using it with the formal application. Normally we would like to have a combo box which will show the name of the article or any thing which we would like that our client should see but internally we like to use the ID the primary key or something else to use for the internal purpose. So here are the steps we are going to follow.

Creating the Design Page For the Combobox Application.
1. Open Visual Studio 2008 or above. Create new Project.
2. Select the language C#, Silverlight Project.
3.Name it Combox.
4.Click ok.
5.Leave the Rest Settings as default.
6.Now open MainPage.xaml. modify the grid add the HorizontalAlignment="Left"
VerticalAlignment="Top"
7. And now And now add the Textblock (Label) like this:
<TextBlock Height="17.09" Grid.Column="0" Grid.Row="0" Width="100.303" Canvas.Left="260" Canvas.Top="38.91" Text="Client Name" TextWrapping="Wrap"
Foreground
="#FF000000" FontSize="16" Margin="12,0,8,5" />
8. In the next column of grid Add the Combobox. like:
<ComboBox x:Name="cmbClient" Grid.Column="1" Grid.Row="0" SelectionChanged="cmbClient_SelectionChanged"></ComboBox>
9. Not going into more Designing Issues. Lets Finish it here. And Start Our Coding.
10. Creating a button so that onclick of that button we can get the
Information of the Client
<Button x:Name="btn" Click="btn_Click" Content="Get Info" Grid.Column="0" Grid.Row="1"></Button>

Now lets create a class with the following Member Properties
Client ID
Client Name
Client Address
Client Mobile number

Now open the MainPage.xaml.cs File And create the following Class
public class MyClients
{
#region Pubic Property
public int pkid;
public string ClientName { get; set; }
public string ClientAddress { get; set; }
public string ClientMobile { get; set; }
#endregion
}

In Next strep we will Creat a List<T> type of variables which will hold the List of MyClients to be displayed in the comboobx. Like:

public static List<MyClients> clientlist = new List<MyClients>();

Now next step is to create a function which will add the MyClients to the List Here is the function.

public voidAddClients()
{
MyClients mynewclient = new MyClients();
mynewclient.ClientAddress = "Jaipur";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Meetu Choudhary";
mynewclient.pkid = 1;
clientlist.Add(mynewclient);
//Adding 2nd CLient
mynewclient = newMyClients();
mynewclient.ClientAddress = "Jaipur";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Anita Choudhary";
mynewclient.pkid = 2;
clientlist.Add(mynewclient);
//Adding 3rd client
mynewclient = new MyClients();
mynewclient.ClientAddress = "Delhi";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Raman Mehta";
mynewclient.pkid = 3;
clientlist.Add(mynewclient);
//Adding 4th client
mynewclient = new MyClients();
mynewclient.ClientAddress = "Delhi";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Gaurav Arora";
mynewclient.pkid = 4;
clientlist.Add(mynewclient);
}

Now we need to call this function in the MainPage so the code of MainPage will now
look like
public MainPage()
{
InitializeComponent();
/*From here I added the code*/
AddClients();
//Telling the combobox which member to be displayed
cmbClient.DisplayMemberPath = "ClientName";
//Telling the Source of the List
cmbClient.ItemsSource = clientlist;
//This line will set the selected item
cmbClient.SelectedIndex = 1;
}

Now We will again declare a public static variable to access the object through out the page.
public static MyClients selectedcl;

Now setting the above variable on the selectionchanged event:
private void cmbClient_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
selectedcl = (MyClients)cmbClient.SelectedItem;
}

and Finally the code for the click event:

private void btn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Client Name : " + selectedcl.ClientName + Environment.NewLine
+ "Client Address : " + selectedcl.ClientAddress + Environment.NewLine
+ "Client Mobile : " + selectedcl.ClientMobile + Environment.NewLine
+ "ID : " + selectedcl.pkid);
}


Now run and see the combox in active Code is attached
Download Code

Saturday, July 25, 2009

Google Code Search

Hey,

Just came across a great link to search codes by Google Here It is

http://www.google.co.in/codesearch

Hope you too will enjoy the searching

One More Great Morning

Meetu: Again a great morning of my life I received the Live meeting accounts and access to e-books
And The Videos Of my MVP Awards Are Already Uploaded Check Them At: My Forums

Thursday, July 16, 2009

Custom paging in gridview

This is a sample of customized Paging the concept implements the logic used in Google for paging the page numbers increases and decreases as in Google.. I have seen that logic and tires to implement it some how i succeeded and now i am sharing it with you all..

in this i have used a menu bar for the customized paging in the pager of a grid view....

the piece of code for the .cs file is as follows and for .aspx files and .cs files please go through the attachments..


using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

binding();
}
}
private void binding()
{
DataTable tblData = new DataTable();
DataColumn col1 = new DataColumn("Data1");
tblData.Columns.Add(col1);

for (int i = 1; i <= 1500; i++)
{
DataRow dr = tblData.NewRow();
dr["Data1"] = i;
tblData.Rows.Add(dr);
}
GridView1.DataSource = tblData;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
Menu pgmenu =(Menu) e.Row.FindControl("Menu1");
int startno, endno;
int selectedpgeno = -1;
if (ViewState["selectedpgno"] == null)
{
startno = 1;
endno = startno + 9;
}
else
{
selectedpgeno = Convert.ToInt32(ViewState["selectedpgno"]);
if ((selectedpgeno - 10) <= 0)
{
startno = 1;
endno = selectedpgeno + 9;
}
else
{
startno = selectedpgeno - 10;
endno = selectedpgeno + 9;
}
}

for (int i = startno; i <= endno; i++)
{
pgmenu.Items.Add(new MenuItem(i.ToString(), (i - 1).ToString()));
}
}
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
ViewState.Add("selectedpgno", e.Item.Text);
GridView1.PageIndex = Convert.ToInt32(e.Item.Value);
binding();
}
protected void Navigate(object sender, CommandEventArgs e)
{
if (e.CommandName == "Next")
{
ViewState.Add("selectedpgno", GridView1.PageIndex + 1);
GridView1.PageIndex = Convert.ToInt32(GridView1.PageIndex + 1);
binding();
}
}
}
Download file

Thanks and Regards
Meetu Choudhary
http://www.msdotnetmentor.com/

Thursday, July 2, 2009

Debug WCF Service : In a tweak

Debugging a WCF Service

Following are the 3-different ways to start debugging a WCF service:

· When you are debugging a client process that calls a service. Here debugger steps into the service also service does not have to be in the same solution as your client application.

· When you are debugging a client process that requests to a service and here service must be a part of your solution.

· When you are using Attach to Process to attach to currently running service. Here debugging begins inside the service.

Debugging with Visual Studio 2008

Using Visual Studio 2008, one can step into a WCF service. One can hit break points inside the WCF service, if the WCF service is in the same solution as the client.

For stepping to work, you must have debugging enabled in the app.config or Web.config file we will discuss later on the limitation and how to enable debugging.

To step into a WCF Service

  1. First you need to create a Visual Studio solution that contains both the WCF client and WCF service projects.
  2. Now from Solution Explorer, right-click the WCF Client project and then click Set as Startup Project.
  3. Then enable debugging in the app.config or web.config file
  4. Mark a breakpoint at the location in the client project where you want to start stepping (just before the WCF service call).
  5. Now, Run to the breakpoint, then begin stepping. The debugger will step into the service automatically.

Limitations of Debugging a WCF Service

1. Stepping Into a Service

The following conditions should be met when you start To step into a service from a client applications:

· Service must be called bys using a synchronous client object.

· One-way contract operation is not allowed.

    • Debugging must be enabled

2. Stepping Out of a Service

The limitations are the same as described the above, in addition, here the debugger must be attached to the client.

This is because while you are debugging a client and step into a service, the debugger remains attached to the service whether you started the client by using Start Debugging or attached to the client by using Attach to Process.

But while you are debugging by attaching to the service, the debugger is not yet attached to the client. In that case, you must first use Attach to Process to attach to the client manually.

Debugging must be enabled

3. Automatic Attach to a Service

Automatically attaching to a service has the following limitations:

· In this case the service must be part of the solution you are debugging.

· The service must be hosted. Which means it may be part of a Web Site Project (File System and HTTP), Web Application Project (File System and HTTP), or WCF Service Library project. WCF Service Library projects can be either Service Libraries or Workflow Service Libraries.

· WCF client must be invoked the service.

· Debugging must be enabled

Enabling Debugging a WCF Service

Use following piece of lines in web.config or asp.config file(s):

<system.web>

<compilation debug="true" />

<system.web>

Note: In case when you use Attach to Process on a service, the debug code is automatically added to the .config file.

How to Debug a Self-Hosted WCF Service?

In simple words WCF service which does not run inside IIS, WCF service Host or ASP.NET Development Server is know as Self-Hosted Service.

To debug such services we need to configure Visual Studio to launch both client and server when you choose Start Debugging on the Debug menu.

How to start both client and host from Visual Studio?

1. Need to create a Visual Studio solution pertaining both the client and server projects.

2. Now configure the solution to start both client and server :

a. From Solution Explorer, right-click the solution name.

b. Click Set Startup Projects.

c. In Solution from Properties dialog box, select Multiple Startup Projects.

d. Click Action and choose Start from the Multiple Startup Projects grid, on the line that corresponds to the server project also on the line that corresponds to the client project, click Action and choose Start.

e. Finally click OK.


Shortcut keys used in Windows operating System

Following are the Shortcut keys used in Windows operating System



Windows system key combinations


F1: Help
CTRL+ESC: Open Start menu
ALT+TAB: Switch between open programs
ALT+F4: Quit program
SHIFT+DELETE: Delete item permanently
Windows Logo+L: Lock the computer (without using CTRL+ALT+DELETE)

Windows program key combinations


CTRL+C: Copy
CTRL+X: Cut
CTRL+V: Paste
CTRL+Z: Undo
CTRL+B: Bold
CTRL+U: Underline
CTRL+I: Italic

Mouse click/keyboard modifier combinations for shell objects


SHIFT+right click: Displays a shortcut menu containing alternative commands
SHIFT+double click: Runs the alternate default command (the second item on the menu)
ALT+double click: Displays properties
SHIFT+DELETE: Deletes an item immediately without placing it in the Recycle Bin

General keyboard-only commands


F1: Starts Windows Help
F10: Activates menu bar options
SHIFT+F10 Opens a shortcut menu for the selected item (this is the same as right-clicking an object
CTRL+ESC: Opens the Start menu (use the ARROW keys to select an item)
CTRL+ESC or ESC: Selects the Start button (press TAB to select the taskbar, or press SHIFT+F10 for a context menu)
CTRL+SHIFT+ESC: Opens Windows Task Manager
ALT+DOWN ARROW: Opens a drop-down list box
ALT+TAB: Switch to another running program (hold down the ALT key and then press the TAB key to view the task-switching window)
SHIFT: Press and hold down the SHIFT key while you insert a CD-ROM to bypass the automatic-run feature
ALT+SPACE: Displays the main window's System menu (from the System menu, you can restore, move, resize, minimize, maximize, or close the window)
ALT+- (ALT+hyphen): Displays the Multiple Document Interface (MDI) child window's System menu (from the MDI child window's System menu, you can restore, move, resize, minimize, maximize, or close the child window)
CTRL+TAB: Switch to the next child window of a Multiple Document Interface (MDI) program
ALT+underlined letter in menu: Opens the menu
ALT+F4: Closes the current window
CTRL+F4: Closes the current Multiple Document Interface (MDI) window
ALT+F6: Switch between multiple windows in the same program (for example, when the Notepad Find dialog box is displayed, ALT+F6 switches between the Find dialog box and the main Notepad window)

Shell objects and general folder/Windows Explorer shortcuts


For a selected object:
F2: Rename object
F3: Find all files
CTRL+X: Cut
CTRL+C: Copy
CTRL+V: Paste
SHIFT+DELETE: Delete selection immediately, without moving the item to the Recycle Bin
ALT+ENTER: Open the properties for the selected object

General folder/shortcut control


F4: Selects the Go To A Different Folder box and moves down the entries in the box (if the toolbar is active in Windows Explorer)
F5: Refreshes the current window.
F6: Moves among panes in Windows Explorer
CTRL+G: Opens the Go To Folder tool (in Windows 95 Windows Explorer only)
CTRL+Z: Undo the last command
CTRL+A: Select all the items in the current window
BACKSPACE: Switch to the parent folder
SHIFT+click+Close button: For folders, close the current folder plus all parent folders

Windows Explorer tree control


Numeric Keypad *: Expands everything under the current selection
Numeric Keypad +: Expands the current selection
Numeric Keypad -: Collapses the current selection.
RIGHT ARROW: Expands the current selection if it is not expanded, otherwise goes to the first child
LEFT ARROW: Collapses the current selection if it is expanded, otherwise goes to the parent

Properties control


CTRL+TAB/CTRL+SHIFT+TAB: Move through the property tabs

Accessibility shortcuts


Press SHIFT five times: Toggles StickyKeys on and off
Press down and hold the right SHIFT key for eight seconds: Toggles FilterKeys on and off
Press down and hold the NUM LOCK key for five seconds: Toggles ToggleKeys on and off
Left ALT+left SHIFT+NUM LOCK: Toggles MouseKeys on and off
Left ALT+left SHIFT+PRINT SCREEN: Toggles high contrast on and off

Microsoft Natural Keyboard keys


Windows Logo: Start menu
Windows Logo+R: Run dialog box
Windows Logo+M: Minimize all
SHIFT+Windows Logo+M: Undo minimize all
Windows Logo+F1: Help
Windows Logo+E: Windows Explorer
Windows Logo+F: Find files or folders
Windows Logo+D: Minimizes all open windows and displays the desktop
CTRL+Windows Logo+F: Find computer
CTRL+Windows Logo+TAB: Moves focus from Start, to the Quick Launch toolbar, to the system tray (use RIGHT ARROW or LEFT ARROW to move focus to items on the Quick Launch toolbar and the system tray)
Windows Logo+TAB: Cycle through taskbar buttons
Windows Logo+Break: System Properties dialog box
Application key: Displays a shortcut menu for the selected item


Microsoft Natural Keyboard with IntelliType software installed


Windows Logo+L: Log off Windows
Windows Logo+P: Starts Print Manager
Windows Logo+C: Opens Control Panel
Windows Logo+V: Starts Clipboard
Windows Logo+K: Opens Keyboard Properties dialog box
Windows Logo+I: Opens Mouse Properties dialog box
Windows Logo+A: Starts Accessibility Options (if installed)
Windows Logo+SPACEBAR: Displays the list of Microsoft IntelliType shortcut keys
Windows Logo+S: Toggles CAPS LOCK on and off


Dialog box keyboard commands


TAB: Move to the next control in the dialog box
SHIFT+TAB: Move to the previous control in the dialog box
SPACEBAR: If the current control is a button, this clicks the button. If the current control is a check box, this toggles the check box. If the current control is an option, this selects the option.
ENTER: Equivalent to clicking the selected button (the button with the outline)
ESC: Equivalent to clicking the Cancel button
ALT+underlined letter in dialog box item: Move to the corresponding item

The above Shortcut keys APPLIES TO


Windows Server 2008 Datacenter
Windows Server 2008 Enterprise
Windows Server 2008 Standard
Microsoft Windows Server 2003, Datacenter Edition (32-bit x86)
Microsoft Windows Server 2003, Enterprise x64 Edition
Microsoft Windows Server 2003, Enterprise Edition (32-bit x86)
Microsoft Windows Server 2003, Enterprise Edition for Itanium-based Systems
Microsoft Windows Server 2003, Standard x64 Edition
Microsoft Windows Server 2003, Standard Edition (32-bit x86)
Microsoft Windows 2000 Server
Microsoft Windows Millennium Edition
Microsoft Windows 98 Second Edition
Microsoft Windows 98 Standard Edition
Microsoft Windows 95
Windows Vista Business
Windows Vista Enterprise
Windows Vista Home Basic
Windows Vista Home Premium
Windows Vista Starter
Windows Vista Ultimate
Microsoft Windows XP Home Edition
Microsoft Windows XP Professional
Microsoft Windows XP Starter Edition
Microsoft Windows XP Tablet PC Edition

Saturday, June 27, 2009

Empty the Recycle Bin

Empty the Recycle Bin

Ths following code is used to empty the recycle bin using Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio

The namespace we have to use is:

using System.Runtime.InteropServices;
 
then create an enum for recylceflags like
 
enum RecycleFlgs : uint
{
   SHERB_NOCONFIRMATION = 0x00000001,
   SHERB_NOPROGRESSUI   = 0x00000002,
   SHERB_NOSOUND        = 0x00000004
}
 
creating an extern
 
[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
static extern uint EmptyRecycleBin 
        (IntPtr hwnd, 
        string pszRootPath,
        RecycleFlgs dwFlags);
               
Now the main function to call  the above defined code
 
public static void Main()
{
    uint result = EmptyRecycleBin (IntPtr.Zero, null, 0);
    Console.WriteLine ("Result: {0}", result);
}


Thanks and Regards
Meetu Choudhary
http://www.msdotnetmentor.com/

Thursday, June 18, 2009

Move Cursor to the Last Index in The Texbox

Code for script section in the head

<script type="text/javascript" language="javascript">
function moveindex() {
var me2 = document.selection.createRange();
me2.moveStart("character", 200);
me2.select();
}
</script>

code for calling the function in the body section

<asp:TextBox ID="TextBox1" runat="server" onfocus="moveindex()"/>


Thanks and Regards
Meetu Choudhary

Wednesday, June 17, 2009

Showing Image Dynamically

This piece of code demonstrate that when we take mouse on a particular image the place holder for the image displays the corresponding image... here goes the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

<head>

<title>Meetu Choudhary</title>

Script for head section


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

function showimage(imagename)

{

targetimage.src="images/" + imagename;

}

</script>

</head>

Body will have these contents..


<body>
<table width="694" height="525" border="0">

<tr>

<td width="141" height="95" valign="top">

<img src="images/image1.jpg" onmouseover="showimage('image1.jpg')" width="141" height="93">

</td>

<td width="141">

<img src="images/image2.jpg" width="141" height="93" onmouseover="showimage('image2.jpg')">

</td>

<td width="141">

<img src="images/image3.jpg" width="141" height="93" onmouseover="showimage('image3.jpg')">

</td>

<td width="139">

<img src="images/image4.jpg" width="141" height="93" onmouseover="showimage('image4.jpg')">

</td>

<td width="98">

<img src="images/image5.jpg" width="141" height="93" onmouseover="showimage('image5.jpg')">

</td>

</tr>

<tr>

<td height="424">&nbsp;</td>

<td colspan="3" valign="top">

<img id="targetimage" src="images/image1.jpg" width="420" height="252"/>

</td>

<td>&nbsp;</td>

</tr>

</table>

</body>

</html>


To download the zip folder conating the demo of the article click here



Thanks and Regards

Meetu Choudhary

Thursday, June 11, 2009

Encrypt And Decrypt Using Digital Signatures

Encrypt And Decrypt Using Digital Signatures


Now in continutaion to my earlier artcile the mirroe link of the article here I am going to describe how we can use the digital signatures for the purpose of Encryption and Decryption.

The Following code will show how we can encrypt the plain text.

Encryption


#region Encryption

public string GetEncryptedText(string PlainStringToEncrypt)

{

try

{

string PlainString = PlainStringToEncrypt.Trim();

byte[] cipherbytes = ASCIIEncoding.ASCII.GetBytes(PlainString);

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;

byte[] cipher = rsa.Encrypt(cipherbytes, false);

return Convert.ToBase64String(cipher);

}

catch (Exception e)

{

throw e;

}

}
#endregion

Now once we have encrypted text we need to decrypt it. the following section of code will demonstrate how to decrypt that encrypted text.

Decryption


#region Decryption

public string GetDecryptedText(string EncryptedStringToDecrypt)

{

try

{



try

{

byte[] cipherbytes = Convert.FromBase64String(EncryptedStringToDecrypt);

if (x509_2.HasPrivateKey)

{

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PrivateKey;

byte[] plainbytes = rsa.Decrypt(cipherbytes, false);

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

return enc.GetString(plainbytes);

}

else

{

throw new Exception("Certificate used for has no private key.");

}

}

catch (Exception e)

{

return e.Message;

}

}

catch

{

return EncryptedStringToDecrypt;

}

}
#endregion



Thanks and Regards

Meetu Choudhary

Tuesday, June 9, 2009

How do I specify more than one parameter for my HyperlinkColumn?

How do I specify more than one parameter for my HyperlinkColumn?
================================================================
Many times will developing the applications we come accross the thing that how i can pass more then one parameter in the query string which is genertated by the datagrid or gridviews... once i was developing an application and the same problem came accross at that time i was quite new to ASP.net and was stucked there did lots of googleing and found the answer now today i want to share that piece of code as an example may be i may help you to avoid a bit burdden of yours to find the code

Here i have encoded the querstring or the URL to avoid some unwanted error which are normaly genertaed due to spaces and special characters.
the code follows like

[code]
< asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" >
< Columns >
< asp:TemplateColumn HeaderText="Sample Column" >
< ItemTemplate >
< asp:Hyperlink runat="server" Text=' < %#Container.DataItem("TextVal")% >' NavigateUrl=' < %# "page.aspx?Param1=" & Server.UrlEncode(Container.DataItem("Val1")) & "&Param2=" & Server.UrlEncode(Container.DataItem("Val2"))%>'/>
</itemtemplate >
</asp:TemplateColumn >
</columns >
[/code]




Thanks and regards
Meetu Choudhary

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com