Redirection in javascript

Javascript also gives us facility to redirect the user to a webpage or website. Also it's easy to learn redirection in javascript. It is just one line code that needed to embed in a function of javascript to redirect the user.

Let's see how to perform redirection in javascript. I am going to make a custom function redirectuser().

<script language="javascript" type="text/javascript">
function redirectuser()
{
window.location="www.google.com";
}
</script>

So this is the function redirectuser() is capable of redirecting user from one one webpage to another or redirecting user from one website to another. In the above example I am redirection user to google.com.

Now it’s up to you where you will call this custom function. I am going to call this function over button's onClick event. Let's have a look over how to do this.

<input type="button" value="redirect" onclick="redirectuser();">

So this is the way to perform redirection in javascript using custom made function.
Read more...

Email Validation in Javascript

In this tutorial you will learn email validation in javascript. While developing a form for web page, it is common requirement to validate the email address. Now let's look how to implement email validation in javascript.

<html>
<head>
<title>Email validation in javascript</title>


<script language="javascript" type="text/javascript">
function checkEmail() {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form1.users_email.value)){
return (true)
}
alert("Please enter valid email address");
form1.users_email.focus();
return (false)
}
</script>

</head>


Now let’s see how to call this function to achieve validation of email address in javascript. I am going to call this function on button's onClick event.


<body>
<form name="form1">
<input type="text" name="users_email" id="users_email" class="boxpink"/><br />
<input type="button" value="submit" onclick="return checkEmail();">
</form>
</body>
</html>

So this is the way to implement email validation in javascript.
Read more...

Getting current page name from complete webpage url

In asp.net once a requirement comes to me to get the current web page name from complete web page url. I have done it using C# code behind and now I want to share my experience with you.

protected void Page_Load(object sender, EventArgs e)

{
string str = Request.RawUrl;
int n = str.LastIndexOf('/');
string pagename = str.Substring(n + 1, str.Length - n - 1);
lbl_Pagename.Text= pagename;
}

So this is the way to get the current web page name from complete web page url in C# code behind.
Read more...

The project system components are not installed on this computer. Please re-install Visual Studio

Some times you got this error

The project system components are not installed on this computer. Please re-install Visual Studio

It's solution is quite easy, just follow the below mentioned steps

  • Go To : start | Run
Type the command mentioned below
  • devenv /resetskippkgs
So this is the way to solve the error 

The project system components are not installed on this computer. Please re-install Visual Studio
Read more...

Check all/Uncheck all checkboxes in javascript

In this tutorial we will learn how to check all and uncheck all checkboxes using javascript. Actually we want to check all and uncheck all checkboxes in a php/asp webpage, as you already know php/asp webpage access the form field using its name attribute, so in this tutorial we will check all and uncheck all checkboxes using the id attribute of the checkbox so that you doesn't feel any difficulty to send form checkboxes data from one page to another. Let’s have a look

<html>

<head>

<title> Check all/Uncheck all checkboxes in javascript for php webpages</title>

<script language="JavaScript" type="text/javascript">
function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}
function UnCheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
</script>
</head>
<body>
<form name="myform" action="checkboxes.asp" method="post">

<input type="checkbox" id="check_list" name="chk_Asp" value="1">ASP<br>
<input type="checkbox" id="check_list" name="chk_Php" value="2">PHP<br>
<input type="checkbox" id="check_list" name="chk_Javascript" value="3">JavaScript<br>
<input type="checkbox" id="check_list" name="chk_Coldfusion" value="4">Cold Fusion<br>
<input type="checkbox" id="check_list" name="chk_Jquery" value="5">JQuery<br>

<input type="button" name="Check_All" value="Check All" onclick="CheckAll(document.myform.check_list);">

<input type="button" name="Un_CheckAll" value="Uncheck All" onclick="UnCheckAll(document.myform.check_list);">

</body>

If you want to
check all and uncheck all checkboxes by clicking hyperlink then use this

<a href="javascript:CheckAll(document.myform.check_list)"> Check All </a>
<a href="javascript:UnCheckAll(document.myform.check_list)">Un Check All</a>

So this is the way you can
check all and uncheck all checkboxes in javascript for php/asp webpages.

Read more...

Generating random numbers in php

In this php tutorial we will learn how to generate random numbers in php. To generate random numbers in php is a quite easy, just you have to call the built-in php function rand() and that’s it. Rand() will return you the random number, let’s have a look over the example given below.

<?php
$Random_number=rand();

echo $Random_number;

?>

When you run this php script, every time you will get a random number but what about if you want to get random number within a range???? To get a random number within a range is also a quite easy method just you need to pass the two arguments to the rand() function. First argument will be the starting number of the range and second argument will be the ending number of the range, now every time you will get a random number that will lie in this range, let’s have a look over example to clearly understand what I try to explain

$Random_number =rand(1,5);


echo $Random_number;

Now some time you will get 1, some time 2 and some time 3, etc. It will not give you any number less than 1 or greater than 5

So this is the way to generate random numbers in php.



Read more...

Using strpos and stripos function to perform search process on strings in php

In this php tutorial I will teach you how to perform search process on string by using strpos and stripos function .

By default php has a function strpos that searches string within a string. Sometime during development of website in php you might need to search for a phrase within a string then using this built-in strpos function you can perform search process easily.

Sometimes you may want to check existence of something within a string so that after confirming whether it exists or not you will apply some condition in your code. This is just a scenario now it’s up to you where you will use this strpos function.

Let’s have a look over example given below to see the use of strpos function in php.

<?php
$string_to_search="Adeel Fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(strpos($sentence, $string_to_search))
{
echo "$string_to_search exists inside $sentence";
}
else{
echo "not found";
}
?>



This is just an example you can directly assign the content coming from database to the $sentence variable and then perform your search process using this built-in php strpos function.

Now there is a drawback of strpos function and its only drawback is that it is case sensitive. Means if you want to search “Adeel Fakhar” within “Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then it will work fine but if you will search “adeel fakhar” within ”Hello every body, wish you all best of luck, Regards, Adeel Fakhar” then strpos is unable to find this, to get rid of this case sensitivity issue we have a built-in php function stripos that works same like strpos but additionally it is case insensitive. Let’s have a look over example given below

<?php
$string_to_search="adeel fakhar";
$sentence="Hello every body, wish you all best of luck, Regards, Adeel Fakhar";

if(stripos($sentence, $string_to_search))
{
echo "stripos function works";
}
else{
echo "not found";
}
?>

In the above example it will print stripos function works.

So this is the way to perform search process of a string within a string in php using strpos and stripos.

I hope you’ve found this php tutorial very handy. Thanks for reading this.

Read more...

Sending Html emails in Asp.net using C#

In the previous example we have learnt how to send emails in Asp.net using C# and now in this example we will learn how to send html emails in Asp.net using C#.

The procedure is Quite same to the previous example just you needed to create a function that will return string to us, in example mentioned below that function is protected string Bodytext(). Secondly you have to call this function like the same way I am calling in the example given below msg.Body = Bodytext(); and then you have to mention this line msg.IsBodyHtml = true; in your C# code

Let’s have a look over the example that will demonstrate how to send the Html emails in asp.net using C#

Sending_Html_Email.aspx


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;
using System.Net; //Use for sending Emails
using System.Net.Mail;//Use for sending Emails


public partial class Examples_Sending_Html_Email : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btn_Submit_Click(object sender, EventArgs e)
{
sendEmail();
}

//Function to send Emails in ASP.NET using C#

protected string Bodytext()
{
string Text = "";
Text = "

" + txt_Message.Text + "

";
return Text;
}
public void sendEmail()
{
MailMessage msg = new MailMessage(txt_From.Text,txt_To.Text);
msg.CC.Add(txt_Cc.Text);
msg.Bcc.Add(txt_Bcc.Text);
msg.Subject = txt_Subject.Text;
msg.Body = Bodytext();
msg.Subject = txt_Subject.Text;
msg.IsBodyHtml = true;
SmtpClient yourSmptpclient = new SmtpClient("localhost");
try
{
yourSmptpclient.Send(msg);
}
catch(Exception Exp)
{
throw Exp;
}
}
}


So this is the way to send HTML Emails in Asp.net Using C# Read more...

Sending Email in ASP.NET using C#

In this tutorial we will learn how to send emails in ASP.Net using C#. To send email from webpage in asp.net is a common and most demanding requirement now days.

Asp.Net use System.Net.Mail namespace to send emails.

Now let’s have a look over example given below that will teach us how to send emails in asp.net using C#

Send_Email.aspx



<body>
<form id="form1" runat="server">
<div>
<table width="600" cellpadding="2" cellspacing="2" border="0">
<tr>
<td colspan="2">

<strong>
Sending Emails in ASP.NET using C#

</strong>
</td>

</tr>

<tr>
<td><strong>To</strong></td><td><asp:TextBox runat="server" ID="txt_To" Width="220px"></asp:TextBox></td>
</tr>

<tr>
<td><strong>Cc</strong></td><td><asp:TextBox runat="server" ID="txt_Cc" Width="220px"></asp:TextBox></td>
</tr>

<tr>
<td><strong>Bcc</strong></td><td><asp:TextBox runat="server" ID="txt_Bcc" Width="220px"></asp:TextBox></td>
</tr>

<tr>
<td><strong>From</strong></td><td><asp:TextBox runat="server" ID="txt_From" Width="220px"></asp:TextBox></td>
</tr>

<tr>
<td><strong>Subject</strong></td><td><asp:TextBox runat="server" ID="txt_Subject" Width="380px"></asp:TextBox></td>
</tr>

<tr>
<td><strong>Message</strong></td><td><asp:TextBox runat="server" ID="txt_Message" TextMode="MultiLine" Rows="7" Columns="45"></asp:TextBox></td>
</tr>

<tr>
<td> </td><td><asp:Button runat="server" ID="btn_Submit" Text="Send Email"
onclick="btn_Submit_Click" /></td>
</tr>
</table>

</div>
</form>
</body>


Send_Email.aspx.cs

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;
using System.Net; // Namespace used to send email
using System.Net.Mail; //Namespace used to send email


public partial class Exmaples_Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btn_Submit_Click(object sender, EventArgs e)
{
sendEmail();
}

//Function to send Emails in ASP.NET using C#
protected void sendEmail()
{
MailMessage msg = new MailMessage(txt_From.Text,txt_To.Text);
msg.CC.Add(txt_Cc.Text);
msg.Bcc.Add(txt_Bcc.Text);
msg.Subject = txt_Subject.Text;
msg.Body = txt_Message.Text;
msg.Subject = txt_Subject.Text;
SmtpClient yourSmptpclient = new SmtpClient("localhost");
try
{
yourSmptpclient.Send(msg);
}
catch(Exception Exp)
{
throw Exp;
}
}
}

//Ends Here

Now let’s understand MailMessage Class Properties

MailMessage Class Properties

From –Email Address of sender
To – Email Address of Recipient(s)
CC – Carbon Copies
BCC – Blind Carbon Copies
Subject – Subject of the Email
ReplyTo – Reply To Email address.
Attachments – Attachments if Any you want.
Body – Body of the Email
IsBodyHtml – Specify whether body contains text or HTML mark up.

Now let’s understand SMTP Class Properties

SMTP Class Properties
Host – Your SMTP Server
EnableSsl – Specify whether you host accepts SSL Connections or not.
Credentials – Valid login credentials for your SMTP server .
UseDefaultCredentials – Set True In order to allow authentication based on the Credentials of the Account used to send emails.
Port – Port No of the SMTP server

So this is the way to send emails in asp.net using C#

Read more...

Disabling Window context menu/ mouse right click in javascript

In this javascript tutorial we will learn how to disable the window context menu which comes when user right click over the webpage. Sometimes programmers disable the mouse right click so that window context menu cannot be opened but by pressing using window context menu button in keyboard (normally located at left of Ctrl button) user can still open the window context menu. So let's see how to disable this in javascript

You can disable window context menu by using oncontextmenu event handler in the body tag of your web page like given below

<body oncontextmenu="return false;">

So this is the way to disable mouse right click as well as disable the window context menu in javascript.
Read more...

Out of range value adjusted for column error in php

Sometimes using Mysql 5 with php we got this error Out of range value adjusted for column. Normally this error comes when you are using an auto increment field in your mysql table and you are trying to insert values from php code in this mysql table which has auto increment field.

To avoid this error Out of range value adjusted for column there are possible three solutions but I prefer solution 1 and solution 2.

Solution 1

Use functionality of SQL_MODE


Just Login to the mysql shell and use this command to avoid the error

SET GLOBAL SQL_MODE=”;

It will fix your problem.

Solution 2

Modification in insert query

Sometimes our website hosting company (incase if website is hosted by website hosting company) doesn’t give us permission to use SQL_MODE or sometimes we want to quicker solve this error without contacting the hosting company of our website then use insert query like this

$sql="insert into student values('Adeel', 'Fakhar')";

Instead of $sql="insert into student values('', 'Adeel', 'Fakhar')";

Solution 3

Move back to Mysql 4

So these are the ways to avoid Out of range value adjusted for column error in php.
Read more...

Force all hyperlinks tags to target a new window

In this javascript tutorial we will learn how to force all hyperlink tags to target a new window. Sometimes we want to target all hyperlink tags to target a new window, normally in case of RSS Feeds.

Let’s consider we have a webpage where we have 100 hyperlinks of RSS feeds and these 100 hyperlinks are opening in a parent window, now we want to target these hyperlinks in a new window so without going in each and every hyperlink and write this code target="_blank" just use this below mention javascript function and call this javascript function in body onload event then all the hyperlinks will target a new window.


function ForceLinks()

{
// It will tell u how many no of tags your code have
var linkslength= document.getElementsByTagName('a').length;

// Putting tag in links variable to use it for array purpose
var links=document.getElementsByTagName('a');

for(var i = 0; i < linkslength; ++i)

{

links[i].setAttribute('target','_blank');

}

}

Now just call this function in your body onload event<body önload="ForceLinks();"> </body>

So this is the way we can force all hyperlink tags to target a new window in javascript.
Read more...

Add to Favorites/Bookmark in javascript

In this tutorial we will learn how to add webpage to the Favorites or how to bookmark a webpage. Let's have a look over the code listed below

<script language="javascript">
function addfav()
{
if (document.all)
{
window.external.AddFavorite
("http://www.nice-tutorials.blogspot.com","Nice Programming Tutorials")
}
}
</script>

I make a custom function and give it a name addfav() whcih will be responsible to bookmark a webpage or add to favorites. Now i am going to call this function by clicking the hyperlink. Let's have a look over the code mentioned below

<a href="javascript:addfav();">Bookmark Us</a>

So this is the way we can add webpage to the Favorites or we can bookmark a webpage in javascript.

Happy Coding

Read more...

check all/uncheck all check boxes in gridview using C# code


In this asp.net tutorial we will learn how to check all/uncheck all check boxes in gridview using C# code.

I can check all/uncheck all check boxes in gridview using javascript code that will work quite fine in all major web browsers such as Google Chrome, Internet Explorer, Opera and Mozilla FireFox but at the same time I also know most of the people want to do this using C# code. So this tutorial is for those people.

Let’s have a look over asp page

Checkall_uncheckall.aspx

<form id="form1" runat="server"> <div>


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%" GridLines="None" HeaderStyle-HorizontalAlign="Left" HeaderStyle-VerticalAlign="Top"><Columns>

<asp:TemplateField HeaderStyle-Width="5%">

<HeaderTemplate>
<asp:CheckBox ID="chkBox2" runat="server" Visible="true" AutoPostBack="true" OnCheckedChanged="chkBox2_CheckedChanged"/>

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox ID="chkBox" runat="server" Visible="true"/>

<asp:Label ID="lbl_Id" runat="server" Visible="false" Text="<%# Bind('ID') %>"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Roll No">

<ItemTemplate>

<asp:Label ID="lbl_Rollno" runat="server" Text='<%# Bind("RollNo")%>'>

</asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="First Name">

<ItemTemplate>

<asp:Label ID="lbl_Firstname" runat="server" Text='<%# Bind("FirstName")%>'>

</asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name">

<ItemTemplate>

<asp:Label ID="lbl_Lastname" runat="server" Text='<%# Bind("LastName")%>'></asp:Label></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="City"><ItemTemplate><asp:Label ID="lbl_City" runat="server" Text='<%# Bind("City")%>'></asp:Label></ItemTemplate></asp:TemplateField></Columns></asp:GridView>

</div>

</form>

Checkall_uncheckall.aspx.cs


protected void chkBox2_CheckedChanged(object sender, EventArgs e)
{

CheckBox chk = (CheckBox)GridView1.HeaderRow.FindControl("chkBox2");
if (chk.Checked)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("chkBox");
chkrow.Checked = true;
}

}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("chkbox");
chkrow.Checked = false;
}
}
}

//End Here

You have to make chkBox2_CheckedChanged(object sender, EventArgs e) function manually because in gridview you cannot double click on any control or select any control.

Note: - While making CheckedChanged function of any checkbox manually you must take care of one thing that function name must contain checkbox id and after check box id there must be _ and then you have to write CheckedChanged(object sender, EventArgs e) and it should be protected. Also please set AutoPostBack property of textbox to true so that this function can be executed.

I hope you will learn this tutorial, this tutorial is independent of any web browser compatibility because it is using C# code but if you want to use any web browser than you can try Google Chrome web browser. Google Chrome is official web browser of Google.

Anyhow again to the topic, this is the way to check all/uncheck all check boxes in gridview using C# code.

Read more...

Implementing meta tags with master page in asp.net using c#

In this asp.net tutorial I will show you how to implement Meta tags with master pages in asp.net using C#.

The Master Pages introduced in ASP.NET 2.0 are a quite handy feature, however, master pages don't provide a good way to deal with the search engine optimization process of your website.

It is necessary for a webpage that it must have good Meta tags to be ranked well in search engines. This tutorial will show you how to extend @page directive on asp.net pages so that you can implement the meta tags of your need on each content page when you have master page.
I know bundle of methods to implement Meta tags with master pages in asp.net, let’s have a look over different methods.

Method 1

Use page.header control on Page Load event to implement the meta tags with master pages

protected void Page_Load(object sender, EventArgs e)
{

Page.Header.Controls.Add(new LiteralControl("<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>"));

Page.Header.Controls.Add(new LiteralControl("<meta name='description' content=Description of the meta tag will come here.'/>"));

Page.Header.Controls.Add(new LiteralControl("<meta name='keywords' content='first keyword, second keyword, third keyword,etc'/>"));
}

Method 2
protected void Page_Load(object sender, EventArgs e)

{

//For description
HtmlMeta descTag = new HtmlMeta();

descTag.Name = "description";

descTag.Content = "My description for this page";

Header.Controls.Add(descTag);
//For Keywords


HtmlMeta keyTag = new HtmlMeta();

keyTag.Name = "keywords";

keyTag.Content = "first keyword, second keyword, third keyword,etc";

Header.Controls.Add(keyTag);

}

So these are the two methods I normally use to implement meta tags with master pages in ASP.NET using C#.

Enjoy SEO Process and Happy Coding


Read more...

Generating Random Numbers in Asp.Net using C#

In this ASP.NET tutorial I will show you how to generate random numbers in asp.net using c#

Just copy/paste the following code in the .aspx.cs page and enjoy the random numbers

yourpage.aspx.cs

Random RandomClass = new Random();

int RandomNumber = RandomClass.Next(4, 14);

TextBox1.Text = Convert.ToString(RandomNumber);

// RandomClass.Next(4, 14) means you will get any random number between/ within this range.

So this is the way we can get random numbers in asp.net using c#
Read more...

Export gridview to excel in asp.net using c#

In this asp.net tutorial I will teach you how to export gridView to excel.

Let’s have a look over code of our aspx page

Gridview_to_excel.aspx

<form id="form1" runat="server">


<div>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
onrowdatabound="GridView1_RowDataBound" Width="100%" GridLines="None" HeaderStyle-HorizontalAlign="Left" HeaderStyle-VerticalAlign="Top">

<Columns>

<asp:TemplateField HeaderText="Roll No">

<ItemTemplate>

<asp:Label ID="lbl_Rollno" runat="server" Text='<%# Bind("RollNo")%>'>
</asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="First Name">

<ItemTemplate>

<asp:Label ID="lbl_Firstname" runat="server" Text='<%# Bind("FirstName")%>'>
</asp:Label>

</ItemTemplate>

</asp:TemplateField>


<asp:TemplateField HeaderText="Last Name">

<ItemTemplate>

<asp:Label ID="lbl_Lastname" runat="server" Text='<%# Bind("LastName")%>'>
</asp:Label>

</ItemTemplate>

</asp:TemplateField>


<asp:TemplateField HeaderText="City">

<ItemTemplate>

<asp:Label ID="lbl_City" runat="server" Text='<%# Bind("City")%>'>
</asp:Label>

</ItemTemplate>


</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="btn_excel" runat="server" onclick="btn_excel_Click" Text="Export to Excel"> </asp:Button>

</form>

The above mentioned code is very clear, We are using GridView Control in our web page and assigning data to gridview from database. After GridView control we have an asp button and its onClick event we are calling our custom function that will export data from gridview to excel.

Let’s Have a look over its .cs page

Gridview_to_excel.aspx.cs

Please add these namespaces in the list of namespaces so that we can successfully export data from grid view to excel.

using System.Text;
using System.IO;

protected void Page_Load(object sender, EventArgs e)

{

if (!Page.IsPostBack)

{

BindData();

}

}

private void BindData()

{

string query = "SELECT * FROM Students";

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);

DataSet ds = new DataSet(); ad.Fill(ds, "Students");

GridView1.DataSource = ds;

GridView1.DataBind();

}

private string ConnectionString

{

get

{

return @"Server=localhost;Database=YourDatabase;Trusted_Connection=true";

}

}



public override void VerifyRenderingInServerForm(Control control)
{
/* Its Confirms that an HtmlForm control is rendered for the specified .net server control at run time. */
}

public static void Export(string fileName, GridView gv)
{
string style = @"<style> .text { mso-number-format:\@; } </style> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";

using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();

// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}

// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}

// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}

// render the table into the htmlwriter
table.RenderControl(htw);
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is Label)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
}
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}

if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
protected void btn_excel_Click(object sender, EventArgs e)
{
//Export the grid data to excel sheet
Export("MyExcelfile.xls", this.GridView1);
}


PrepareControlForExport() function will restrict controls to export themselves to excel, mean if you have textbox control in gridview then this function will not export textbox from gridview to excel, actually it will export textbox data from gridview to excel.

If you will not use function VerifyRenderingInServerForm(Control control) in your C# code then you will get following error depends upon the controls you are using in the .aspx page

Control 'your_control' of type 'control_type' must be placed inside a form tag with runat=server.

This is quite confusing, since your GridView and all its controls already inside the form tags containing attribute runat=”server”, So please use this VerifyRenderingInServerForm(Control control) function in your C# Code to remove this error.

In export function the first line of code is

string style = @"<style> .text { mso-number-format:\@; } </style> ";

Actually I use this text style to accurately export data from gridview to excel because in some cases users have numeric or floting type data in gridview such as 109876,54 or 1.987654. by default the numeric or floting point data type style in gridview is mso-number-format:\@ so we have to convert this style to text that’s why I use this line of code and also assign text style to those numeric or floting point data containing fields in Row Bound event of GridView

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//If the first template field of gridview contains
//numeric or floting point data then use this code
e.Row.Cells[0].Attributes.Add("class", "text");

}
}

So now feel free to export grid view data to excel and it will show you exact data without converting it into such as +E.01

If you want to export gridview data to excel within an UpdatePanel then please read this post Export gridview to excel within an UpdatePanel

This is the way to export grid view data to excel Read more...

Accessing Controls of Previous Page in C#

In this ASP.NET tutorial I will teach you how to get the previous page’s controls that in most of the cases you want to access.

Before arrival of Asp.Net 2.0, accessing the previous page's controls from a given page was almost not possible though we could get the controls’ values and transferred these values from one page to another using Sessions, HttpContext, even cookies in some scenarios.

Asp.Net 2.0 comes with a quite handy feature which is PreviousPage property. This is a public property of the Page class, and refers to the PreviousPage instance. Using this property, we can access the previous page's public properties.

We can get previous page's controls too with all its properties, so it’s up to you what you will do after accessing the previous page's controls that you want to access in your page.

I will use a custom function FindControl() that takes two parameters to access the controls of previous page. Let’s have a look over below mentioned example; we have a web page named as firstpage.aspx that has a text box and a button control. Please note that the button's PostBackUrl property is set to another page, it means when the button is clicked, the current web form will post back to the webpage mentioned in PostBackUrl property of the button.

In simple words if button is clicked the current form is submitted to the web page mentioned in the PostBackUrl property of the button.

Page1.aspx

<form id="Form1" runat="server">

<div>

<asp:TextBox ID="txt_Name" runat="server" Text="Adeel Fakhar">

</asp:TextBox>

<asp:Button ID="Button1" runat="server" PostBackUrl="~/page2.aspx" Text="Button" />

</div>

</form>


Now let’s have a look over page2.aspx where we are getting previous page’s controls.

Page2.aspx.cs


public partial class page1: System.Web.UI.Page
{
private TextBox myTextbox;
protected void Page_Load(object sender, EventArgs e)
{
myTextbox= this.FindControl("txt_Name", PreviousPage.Controls) as TextBox;
}


private Control FindControl(string controlID, ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.ID == controlID)
return c;
if (c.HasControls())
{
Control cTmp = this.FindControl(controlID, c.Controls);

if (cTmp != null)

return cTmp;
}
}
return null;
}

Now let’s understand the code of page2.aspx

1) I declare an object (myTextbox) of Textbox class
2) On Page Load event of the page2.aspx, I get the Previous Page’s control that I wanted to get which is txt_Name and assign this Control to the myTextbox using FindControl function, now myTextbox will behave exactly like the previous page's control which is in my case txt_Name.

Now you have got all the properties of the txt_Name in myTextbox, now it’s up to you which property you will get, as an example I am getting its value and assigning it to string variable which is myName

String myName;

myName = myTextbox.text;

So this is the way to access the previous page’s controls in c#
Read more...

Open a Popup window from a gridview asp:hyperlink control in C#

In this asp.net tutorial you will learn how to Popup a window from a gridview asp:hyperlink control. Sometimes suring development you may need to Popup a window from a gridview asp:hyperlink control. Let's have a look over how to do such.

Yourpage.aspx


<asp:GridView ID="GridView1" runat="server" EnableTheming="false" GridLines="None" AutoGenerateColumns="false" Width="100%" OnRowDataBound="GridView1_RowDataBound">
<Columns>

<asp:TemplateField>
<ItemTemplate>
<asp:Label id="lblFormID" runat="server" Text="<%# Bind('ID') %>" Visible="false">

</asp:Label>
<asp:HyperLink ID="hypComment" runat="server" Text="<%# Bind('Comments') %>" style="cursor:pointer;">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


YourPage.aspx.cs

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Now Want to open Popup window from hyper link
string formid = ((Label)e.Row.FindControl("lblFormID")).Text;
urlWithParams = "
yourpage.aspx?id="+formid;
((HyperLink)e.Row.FindControl("hypComment")).Add("OnClick", "window.open('" + urlWithParams + "','PopupWindow','width=400,height=200')");
//Ends Here
}
}

So this is the way to Popup a window from gridview asp:hyperlink control.
Read more...

Calling a javascript function from C# code behind

Sometimes we want to call javascript function from C# code behind, because some time visual studio doesn't show you all events that normally your control should have for calling javascript functions, so to get rid of this problem we call our javascript function from code behind, in this example i am using C# code behind to fire the event and call the javascript function.

Yourpage.aspx

Let's consider this is the javascript function in your aspx page that you want to call from C# code behind.

<script language="javascript">
function alertfunc()
{
alert("This is the way to call the javascript function from C# code behind");
}

<script>


And now for instance this is the dropdownlist in your aspx page and you will call the javascript function by firing its onChange event.

<asp:DropDownList ID="ddl_SearchOption" runat="server" >

<asp:ListItem Text="Muhammad Ali" Value="1"></asp:ListItem>
<asp:ListItem Text="Adeel Fakhar" Value="2"></asp:ListItem>
</asp:DropDownList>

Yourpage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
ddl_SearchOption.Attributes.Add("onChange", "alertfunc()");
}

 
Note:- If you want to write and execute the javascript function from code behind then please refer to this tutorial Learn how to write and execute the javascript code from c# code behind
So this is the way to call the javascript function from C#

Read more...

Getting Internet Explorer Version using C#

Most of the time we may need to get the version of Interet Explorer in web application using c#.

Let's have a look over below mentioned code to get the Internet Explorer's version in c#.

public partial class mywebpage : System.Web.UI.UserControl
{
private float gettingInternetExplorerVersion()
{
// Will the version of IE or a -1 indicating the use of another browser.

float rva = -1;
System.Web.HttpBrowserCapabilities browser = Request.Browser;
if (browser.Browser == "IE")
rva = (float)(browser.MajorVersion + browser.MinorVersion);
return rva;
}
protected void Page_Load(object sender, EventArgs e)
{
double ver = gettingInternetExplorerVersion();
Label1.Text = ver;
}
}

so this is the way to get the Internet Explorer version in C# Read more...

Getting windows username in javascript

sometimes you want to get windows username in your application which is running on intranet. To get the windows username of currently login user i am using javascript.

Here's the code to get windows username in javascript.


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

var WshNetwork = new ActiveXObject("WScript.Network");

alert (WshNetwork.UserName);

</script>

This code snippet will work only in Internet Explorer because Internet Explorer deals with ActiveX Controls. ActiveX is famous for bad security that's why web browsers such as Mozilla Firefox, Google Chrome doesn;t support this.

To get the windows username through just JavaScript is also a big security risk. Therefore it uses ActiveX to get windows username of currently login user. Read more...