Friday, December 31, 2010

What is the difference between String and string in C#

string :
------

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:


String :
------

A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object


Difference between string & String :
---------- ------- ------ - ------

the string is usually used for declaration while String is used for accessing static string methods

we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.

we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.

we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.

Wednesday, December 29, 2010

Default text disappear from textbox with javascript

//form action="http://www.domain.com" method="post">
//input type="text" size="25" value="Enter Your Default Text Here" onFocus="if(this.value == 'Enter Your Default Text Here') {this.value = '';}" //onBlur="if (this.value == '') {this.value = 'Enter Your Default Text Here';}" />
//input type=submit value=Submit>
///FORM>

Monday, December 27, 2010

Javascript Open a Window Full Size (Mazimized)

function f_open_window_max( aURL, aWinName )
{
var wOpen;
var sOptions;

sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';

wOpen = window.open( '', aWinName, sOptions );
wOpen.location = aURL;
wOpen.focus();
wOpen.moveTo( 0, 0 );
wOpen.resizeTo( screen.availWidth, screen.availHeight );
return wOpen;
}

Thursday, December 23, 2010

Javascript function for horizontal center align in asp.net

function SetDivPosition(tbl,hgt)
{
document.getElementById(tbl).style.height = ((document.body.clientHeight - hgt)/2) + "px";

}

//Call this function into the OnLoad() and OnResize() event of body tag.

Wednesday, December 15, 2010

Difference between Website and Web Application in ASP.NET

Web site in Visual Studio 2005:


A web site is just a group of all files in a folder and sub folders. There is no project file. All files under the specific folder - including your word documents, text files, images etc are part of the web site.

You have to deploy all files including source files (unless you pre compile them) to the server. Files are compiled dynamically during run time.

To create a "web site", you need to use the menu File > New > Website

You will have the option to choose either one of the following location types:

# File System - Allows you to choose a folder to put all the files.
# Http - Allows you to choose a virtual directory to put the files.
# FTP - Allows you to choose an ftp location.

In any of the above cases, no project file is created automatically. Visual Studio considers all files under the folder are part of the web site.

There will be no single assembly created and you will nto see a "Bin" folder.

The benefits of this model is, you do not need a project file or virtual directory to open a project. It is very handy when you share or download code from the internet. You just need to copy the downloaded code into a folder and you are ready to go!




Web Application Project in Visual Studio 2005:


Microsoft introduced the "web site" concept where all files under a web site are part of the site, hoping that the development community is going to love that. In fact, this is very usefull to share code.

However, they did not consider millions of existing web applications where people are comfortable with the "project" based application. Also, there were lot of web applications where several un wanted files were kept under the web site folder. So, the new model did not work well for them.

When people started screaming, Microsoft came up with the answer. On April 7, 2006, they announced "Visual Studio 2005 Web Application Projects" as an Add-On to Visual Studio 2005. This Add-On will allow you to create and use web applications just like the way it used to be in Visual Studio 2003.

The Visual Studio 2005 Web Application Project model uses the same project, build and compilation method as the Visual Studio .NET 2003 web project model.

All code files within the project are compiled into a single assembly that is built and copied in the Bin directory.

All files contained within the project are defined within a project file (as well as the assembly references and other project meta-data settings). Files under the web's file-system root that are not defined in the project file are not considered part of the web project.

Saturday, November 27, 2010

Friday, November 19, 2010

How To Change The Screen Resolution in C#

All programmers are facing common problem is how to change screen Resolution dynamically. In .Net 2005 it's very easy to change the screen resolution. Here We will explain you how can we get the Screen resolution and how we will change the resolution at dynamically and while unloading the page it will come as it was before. In dot net we can access the values of user's screen resolution through the Resolution class. It also affects all running (and minimized) programs.

Page_Load Function

Screen Srn = Screen.PrimaryScreen;
tempHeight = Srn.Bounds.Width;
tempWidth = Srn.Bounds.Height;
Page.ClientScript.RegisterStartupScript
(this.GetType(), "Error", "");
//if you want Automatically Change res.at page load.
//please uncomment this code.

if (tempHeight == 600)//if the system is 800*600 Res.then change to
{
FixHeight = 768;
FixWidth = 1024;
Resolution.CResolution ChangeRes =
new Resolution.CResolution(FixHeight, FixWidth);
}

Change Resoultion in C# switch (cboRes.SelectedValue.ToString())
{
case "800*600":
FixHeight = 800;
FixWidth = 600;
Resolution.CResolution ChangeRes600 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1024*768":
FixHeight = 1024;
FixWidth = 768;
Resolution.CResolution ChangeRes768 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
case "1280*1024":How To Change The Screen Resolution in C#
FixHeight = 1280;
FixWidth = 1024;
Resolution.CResolution ChangeRes1024 =
new Resolution.CResolution(FixHeight, FixWidth);
break;
}

Tuesday, November 16, 2010

How to close active child form into the MDI application

Form[] charr = this.MdiChildren;
foreach (Form chform in charr)
chform.Close();

String Format for DateTime in C#

String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.

[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.

[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:

[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting
In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.

[C#]
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime

Monday, November 15, 2010

Drawing a transparent button in C# winforms

public class ImageButton : ButtonBase, IButtonControl
{
public ImageButton()
{
this.SetStyle(
ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics g = pevent.Graphics;
g.FillRectangle(Brushes.Transparent, this.ClientRectangle);
g.DrawRectangle(Pens.Black, this.ClientRectangle);
}
// rest of class here...
}

Thursday, July 8, 2010

open a new browser window in Windows Forms

private void tsmGoogle_Click(object sender, EventArgs e)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "iexplore";
proc.StartInfo.Arguments = "http://www.google.com/";
proc.Start();
}

Tuesday, July 6, 2010

Import and Export data from SQL Server 2005 to XL Sheet

For uploading the data from Excel Sheet to SQL Server and viceversa, we need to create a linked server in SQL Server.

Expample linked server creation:

Before you executing the below command the excel sheet should be created in the specified path and it should contain the name of the columns.

EXEC sp_addlinkedserver 'ExcelSource2',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
'C:\Srinivas\Vdirectory\Testing\Marks.xls',
NULL,
'Excel 5.0'

Once you executed above query it will crate linked server in SQL Server 2005.

The following are the Query from sending the data from Excel sheet to SQL Server 2005.

INSERT INTO emp SELECT * from OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\text.xls','SELECT * FROM [sheet1$]')

The following query is for sending the data from SQL Server 2005 to Excel Sheet.

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\text.xls;',
'SELECT * FROM [sheet1$]') select * from emp

Tuesday, June 29, 2010

ASP.NET – Function to Fill Month, Date and Year into Dropdown lists

public void fillMonthList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Month", "Month"));
ddlList.SelectedIndex = 0;

DateTime month = Convert.ToDateTime("1/1/2000");
for (int intLoop = 0; intLoop < 12; intLoop++)
{
DateTime NextMont = month.AddMonths(intLoop);
//ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.Month.ToString()));
ddlList.Items.Add(new ListItem(NextMont.ToString("MMMM"), NextMont.ToString("MMMM")));
}
}

public void fillDayList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Day", "Day"));
ddlList.SelectedIndex = 0;

int totalDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
for (int intLoop = 1; intLoop <= totalDays; intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}

public void fillYearList(DropDownList ddlList)
{
ddlList.Items.Add(new ListItem("Year", "Year"));
ddlList.SelectedIndex = 0;

int intYearName = 1900;
for (int intLoop = intYearName; intLoop <= Convert.ToInt32(DateTime.Now.Year); intLoop++)
{
ddlList.Items.Add(new ListItem(intLoop.ToString(), intLoop.ToString()));
}
}

Thursday, June 10, 2010

How to configure VPN in Windows XP

VPN Overview
A VPN is a private network created over a public one. It’s done with encryption, this way, your data is encapsulated and secure in transit – this creates the ‘virtual’ tunnel. A VPN is a method of connecting to a private network by a public network like the Internet. An internet connection in a company is common. An Internet connection in a Home is common too. With both of these, you could create an encrypted tunnel between them and pass traffic, safely - securely.
If you want to create a VPN connection you will have to use encryption to make sure that others cannot intercept the data in transit while traversing the Internet. Windows XP provides a certain level of security by using Point-to-Point Tunneling Protocol (PPTP) or Layer Two Tunneling Protocol (L2TP). They are both considered tunneling protocols – simply because they create that virtual tunnel just discussed, by applying encryption.
Configure a VPN with XP
If you want to configure a VPN connection from a Windows XP client computer you only need what comes with the Operating System itself, it's all built right in. To set up a connection to a VPN, do the following:
1. On the computer that is running Windows XP, confirm that the connection to the Internet is correctly configured.
• You can try to browse the internet
• Ping a known host on the Internet, like yahoo.com, something that isn’t blocking ICMP
2. Click Start, and then click Control Panel.

3. In Control Panel, double click Network Connections

4. Click Create a new connection in the Network Tasks task pad

5. In the Network Connection Wizard, click Next.

6. Click Connect to the network at my workplace, and then click Next.

7. Click Virtual Private Network connection, and then click Next.
8. If you are prompted, you need to select whether you will use a dialup connection or if you have a dedicated connection to the Internet either via Cable, DSL, T1, Satellite, etc. Click Next.

9. Type a host name, IP or any other description you would like to appear in the Network Connections area. You can change this later if you want. Click Next.

10. Type the host name or the Internet Protocol (IP) address of the computer that you want to connect to, and then click Next.
11. You may be asked if you want to use a Smart Card or not.

12. You are just about done, the rest of the screens just verify your connection, click Next.

13. Click to select the Add a shortcut to this connection to my desktop check box if you want one, if not, then leave it unchecked and click finish.
14. You are now done making your connection, but by default, it may try to connect. You can either try the connection now if you know its valid, if not, then just close it down for now.

15. In the Network Connections window, right-click the new connection and select properties. Let’s take a look at how you can customize this connection before it’s used.
16. The first tab you will see if the General Tab. This only covers the name of the connection, which you can also rename from the Network Connection dialog box by right clicking the connection and selecting to rename it. You can also configure a First connect, which means that Windows can connect the public network (like the Internet) before starting to attempt the ‘VPN’ connection. This is a perfect example as to when you would have configured the dialup connection; this would have been the first thing that you would have to do. It's simple, you have to be connected to the Internet first before you can encrypt and send data over it. This setting makes sure that this is a reality for you.

17. The next tab is the Options Tab. It is The Options tab has a lot you can configure in it. For one, you have the option to connect to a Windows Domain, if you select this check box (unchecked by default), then your VPN client will request Windows logon domain information while starting to work up the VPN connection. Also, you have options here for redialing. Redial attempts are configured here if you are using a dial up connection to get to the Internet. It is very handy to redial if the line is dropped as dropped lines are very common.

18. The next tab is the Security Tab. This is where you would configure basic security for the VPN client. This is where you would set any advanced IPSec configurations other security protocols as well as requiring encryption and credentials.

19. The next tab is the Networking Tab. This is where you can select what networking items are used by this VPN connection.

20. The Last tab is the Advanced Tab. This is where you can configure options for configuring a firewall, and/or sharing.

Connecting to Corporate
Now that you have your XP VPN client all set up and ready, the next step is to attempt a connection to the Remote Access or VPN server set up at the corporate office. To use the connection follow these simple steps. To open the client again, go back to the Network Connections dialog box.
1. One you are in the Network Connection dialog box, double-click, or right click and select ‘Connect’ from the menu – this will initiate the connection to the corporate office.

2. Type your user name and password, and then click Connect. Properties bring you back to what we just discussed in this article, all the global settings for the VPN client you are using.
3. To disconnect from a VPN connection, right-click the icon for the connection, and then click “Disconnect”
Summary
In this article we covered the basics of building a VPN connection using Windows XP. This is very handy when you have a VPN device but don’t have the ‘client’ that may come with it. If the VPN Server doesn’t use highly proprietary protocols, then you can use the XP client to connect with. In a future article I will get into the nuts and bolts of both IPSec and more detail on how to configure the advanced options in the Security tab of this client.
678: The remote computer did not respond.
930: The authentication server did not respond to authentication requests in a timely fashion.
800: Unable to establish the VPN connection.
623: The system could not find the phone book entry for this connection.
720: A connection to the remote computer could not be established.


More on : http://www.windowsecurity.com/articles/Configure-VPN-Connection-Windows-XP.html

Saturday, April 10, 2010

What is Polymorphism?

* Polymorphism is one of the primary characteristics (concept) of object-oriented programming.
* Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
* Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
* Polymorphism is the ability to process objects differently depending on their data types.
* Polymorphism is the ability to redefine methods for derived classes.

Types of Polymorphism

* Compile time Polymorphism
* Run time Polymorphism

Compile time Polymorphism

* Compile time Polymorphism also known as method overloading
* Method overloading means having two or more methods with the same name but with different signatures

Example of Compile time polymorphism

public class Calculations
{
public int add(int x, int y)
{
return x+y;
}
public int add(int x, int y, int z)
{
return x+y+z;
}
}

Run time Polymorphism

* Run time Polymorphism also known as method overriding
* Method overriding means having two or more methods with the same name , same signature but with different implementation

Example of Run time Polymorphism

class Circle
{
public int radius = 0;
public double getArea()
{
return 3.14 * radius * radius
}
}
class Sphere
{
public double getArea()
{
return 4 * 3.14 * radius * radius
}
}

Monday, March 22, 2010

How to use Java Applet into the ASP.NET page

//First download xpiinstall.exe and install into your system.

applet code="JavaFile.class" width="100%" codebase="CodePath" height="40" archive="JavaFile.jar">
param value="CodePath" name="url" />
param value="" name="dataurl" />
/applet>*/

Friday, March 12, 2010

How to create dynamically LinkButton with Literal Control in ASP.NET

Step 1 : First take following control into the .aspx page.

asp:UpdatePanel id="up1" runat="server">
contenttemplate>
asp:Literal ID="lt1" Text="" runat="server">
asp:PlaceHolder ID="ph1" runat="server">
/asp:PlaceHolder>
/contenttemplate>
/asp:UpdatePanel>

Step 2 :
string query = query for fill the dataset;
DataSet ds = new DataSet();
ds = pass the query to retrive data;
int i = 0;
LinkButton lt = new LinkButton();
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
lt = new LinkButton();
lt.ID = "link" + i.ToString();
lt.Text = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ph1.Controls.Add(lt);
ph1.Controls.Add(new LiteralControl("
"));
}

Thursday, March 11, 2010

How to use Ajax : CollapsiblePanelExtender in ASP.NET

//It is simple method, Other properties will be set which you want

Step 1: Take one panel and all the content you want to collapse put into this panel.
Step 2: Set the Collapsed Property true.
Step 3: ExpandControlID/CollapseControlID : The Controls that will expand or collapse the panel on a click, respectively. If these values are the same, the panel will automatically toggle its state on each click.
Step 4: TargetControlID is PanelID
Step 5: Select Panel and Set the Property SuppressPostBack="True"

How to use Ajax : Hovermenu Extender in ASP.NET

// It is a simple method, Other properties set by you which you want

Step 1. Take the control that the extender is targeting.When the mouse cursor is over this control,the hover menu popup will be displayed.
Step 2. Take one panel to display when mouse is over the target control
Step 3. Set the following properties:
TargetControlID = "ID of the panel or control which display when mouse is over the target control"
PopupControlID = "ID of the control that the extender is targeting"
PopupPosition = Left (Default), Right, Top, Bottom, Center.

Wednesday, March 3, 2010

Web Application : How to upload multiple images at a time

//First add image control into the web form how many you want to upload images at a time
//Add one button
//Write the below code into the button_click event

if (FileUpload1.HasFile)
{
string imagefile = FileUpload1.FileName;

if (CheckFileType(imagefile) == true)
{
Random rndob = new Random();
int db = rndob.Next(1, 100);
filename = System.IO.Path.GetFileNameWithoutExtension(imagefile) + db.ToString() + System.IO.Path.GetExtension(imagefile);

String FilePath = "images/" + filename;
FileUpload1.SaveAs(Server.MapPath(FilePath));

objimg.ImageName = filename;
Image1();

if (Session["imagecount"].ToString() == "1")
{
Img1.ImageUrl = FilePath;
ViewState["img1"] = FilePath;
}
else if (Session["imagecount"].ToString() == "2")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = FilePath;
ViewState["img2"] = FilePath;
}
else if (Session["imagecount"].ToString() == "3")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = FilePath;
ViewState["img3"] = FilePath;
}
else if (Session["imagecount"].ToString() == "4")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = FilePath;
ViewState["img4"] = FilePath;
}
else if (Session["imagecount"].ToString() == "5")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = ViewState["img4"].ToString();
Img5.ImageUrl = FilePath;
ViewState["img5"] = FilePath;
}

}


}
//execption handling
else
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "";
lblErrMsg.Text = "please select a file";
}

}

//if file extension belongs to these list then only allowed
public bool CheckFileType(string filename)
{
string ext;
ext = System.IO.Path.GetExtension(filename);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".jpeg":
return true;
case ".jpg":
return true;
case ".bmp":
return true;
case ".png":
return true;
default:
return false;
}
}

How to submit a form on pressing enter key

function clickButton(e, buttonid)
{
var bt = document.getElementById(buttonid);
if (typeof bt == 'object'){
if(navigator.appName.indexOf("Netscape")>(-1)){
if (e.keyCode == 13){
bt.click();
return false;
}
}
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
{
if (event.keyCode == 13){
bt.click();
return false;
}
}
}
}

//Call this function on last text box of a form with onKeyPress="clickButton(this)"

Wednesday, February 10, 2010

How to select and deselect checkbox field into the GridView

//JavaScript function for Select and Deselect checkbox field in GridView

function SelectDeselectAll(chkAll)
{
var a = document.forms[0];
var i=0;
for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
a[i].checked = chkAll.checked;
}
}
}
function DeselectChkAll(chk)
{
var c=0;
var d=1;
var a = document.forms[0];
//alert(a.length);
if(chk.checked == false)
{
document.getElementById("chkAll").checked = chk.checked;
}
else
{

for(i=0;i lessthansign a.length;i++)
{
if(a[i].name.indexOf("chkItem") != -1)
{
if(a[i].checked==true)
{
c=1;
}
else
{
d=0;
}
}
}

if(d != 0)
{

document.getElementById("chkAll").checked =true;
}
}
}

//How to use this function

asp:TemplateField>
input id="Checkbox1" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>
/asp:GridView> columns>
asp:TemplateField>headertemplate>
input id="chkAll" runat="server" onclick="javascript:SelectDeselectAll(this);" type="checkbox" />
/HeaderTemplate>

How to use Ajax Validator Collout Extender

Steps:-

Step 1 : Insert any validation control with textbox
Step 2 : Insert Validator Collout Extender with validation control from the Ajax Control Toolkit
Step 3 : Set the property of the Validation control : ControlToValidate,ErrorMessage,SetFocusOnError=True,Display=none and Give the proper name to the validation control
Step 4 : Set the ValidationControlID into the Validator collout Extender Property TargetControlID

C# window application : How to validate mobile no.

//First : Simple Method
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == true)
{
if (textBox1.Text.Length < 10) { //do nothing } else { MessageBox.Show("Max 10 chars"); e.Handled = true; } } else { e.Handled = true; } } //Second Method using System.Text.RegularExpressions; private void btnValidatePhoneNumber_Click(object sender, EventArgs e) { Regex re = new Regex("^9[0-9]{9}"); if(re.IsMatch(txtPhone.Text.Trim()) == false || txtPhone.Text.Length>10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txtPhone.Focus();
}
}

//With the help of JavaScript
function phone_validate(phone)
{
var phoneReg = ^((\+)?(\d{2}[-]))?(\d{10}){1}?$;
if(phoneReg.test(phone) == false)
{
alert("Phone number is not yet valid.");
}
else
{
alert("You have entered a valid phone number!");
}
}

Tuesday, February 9, 2010

How to load Image in C# and set properties of the Picture Box

Create a C# application drag a picture Box, four buttons and open file dialog on the form.
Write code on btn_browse Button click
-----------------------------------------
private void btn_browse_Click(object sender, System.EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(open.FileName);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
Write code on btn_StretchImage Button click
------------------------------------------------
private void btn_StretchImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
}
Write code on btn_AutoSize Button click
-------------------------------------------------
private void btn_AutoSize_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
}
Write code on btn_CenterImage Button click
--------------------------------------------------
private void btn_CenterImage_Click(object sender, System.EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
}

Thursday, February 4, 2010

C# window application : How to pass the value from one page to another

//In Mdi Form
//Declare the variable, which you want to pass

string userid;
string password;

FormName obj = new FormName(userid,password);
obj.MdiParent = this;
obj.Show();

//In Other Form
//Declare the variable, which you want to pass

string userid;
string password;

public FormName(string uid1,string psw)
{
userid = uid1;
password = psw;
InitializeComponent();
}

Thursday, January 28, 2010

Passing data from one database to another database table (Access) (C#)

string conString = "Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=Backup.mdb;Jet
OLEDB:Database Password=12345";
OleDbConnection dbconn = new OleDbConnection();
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
OleDbCommand dbcommand = new OleDbCommand();

try
{
if (dbconn.State == ConnectionState.Closed)
dbconn.Open();

string selQuery = "INSERT INTO [Master] SELECT * FROM [MS Access;DATABASE="+
"\\Data.mdb" + ";].[Master]";

dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
}
catch(Exception ex) {}

How to create an Access database by using ADOX and Visual C# .NET

Build an Access Database

1. Open a new Visual C# .NET console application.
2. In Solution Explorer, right-click the References node and select Add Reference.
3. On the COM tab, select Microsoft ADO Ext. 2.7 for DDL and Security, click Select to add it to the Selected Components, and then click OK.
4. Delete all of the code from the code window for Class1.cs.
5. Paste the following code into the code window:

using System;
using ADOX;

private void btnCreate_Click(object sender, EventArgs e)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();

cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=D:\\NewMDB.mdb;" +"Jet OLEDB:Engine Type=5");
MessageBox.Show("Database Created Successfully");
cat = null;
}

Wednesday, January 27, 2010

Pager Control for Repeater, DataList

http://www.codeproject.com/KB/custom-controls/CollectionPager.aspx?fid=160845&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=251

Friday, January 22, 2010

How to use Crystal Report into the ASP.NET

using CrystalDecisions.CrystalReports.Engine;
protected void Page_Load(object sender, EventArgs e)
{
ConfigureReport();
}
private void ConfigureReport()
{
ReportDocument mydoc = new ReportDocument();
string reportPath = Server.MapPath("Report.rpt");
mydoc.Load(reportPath);
CrystalReportViewer1.ReportSource = mydoc;
CrystalReportViewer1.DataBind();
}

Disable Typing in Combobox in C# window application

//Disable Typing in Combobox in C# window application
Set the Combobox DropDownStyle property to : DropDownList

How to clear all the textbox/groupbox on single click

public void ClearTextBox(Form f)
{
for (int i = 0; i < f.Controls.Count; i++)
{
if (f.Controls[i] is TextBox)
{
f.Controls[i].Text = "";
}
else if (f.Controls[i] is GroupBox)
{
for (int j = 0; j < f.Controls[i].Controls.Count; j++)
{
if (f.Controls[i].Controls[j] is TextBox)
{
f.Controls[i].Controls[j].Text = "";
}
}
}
}
}
//How to call this function(Into the Submit Button)
Make a object from the Program.cs file.
object.ClearTextBox(this);
//After submit query

Monday, January 18, 2010

Window Application : C# Function for Insert,get data and fill the dropdown list

//To get data from database
string constr;
constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb";
public object getdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
object a;
OleDbCommand cmd = new OleDbCommand(str, con);
a = cmd.ExecuteScalar();
con.Close();
return a;
}
//To inserting data into the database
public void insertdata(string str)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
}
//To fill the dropdownlist
public void dataset(ComboBox ddl, string str)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbDataAdapter dap = new OleDbDataAdapter(str, con);
con.Open();

DataSet ds = new DataSet();
dap.Fill(ds);

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i].ItemArray[0].ToString()))
{
ddl.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString());
}
}
con.Close();
}

Monday, January 4, 2010

URL validation in C# window application

private void TextBox1_Validating(object sender, CancelEventArgs e)
{
System.Text.RegularExpressions.Regex rURL = new System.Text.RegularExpressions.Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
if (txtURL.Text.Length > 0)
{
if (!rURL.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid URL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtURL.SelectAll();
}
}
}

Email validation in C# window application

private void TextBox1_Validating(object sender, CancelEventArgs e)
{
System.Text.RegularExpressions.Regex rEmail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txtEmail.Text.Length > 0)
{
if(!rEmail.IsMatch(txtEmail.Text))
{
MessageBox.Show("Please provide valid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtEmail.SelectAll();
}
}
}

Validation for textbox : C# window application

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 47 && e.KeyChar <= 58) || (e.KeyChar == 46) || (e.KeyChar == 8))
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("Please enter only number");
}
}