Could not load file or assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencie

In this tutorial you will learn how to get rid of this Could not load file or assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified error. Today when I tried to run one of my .aspx page in my web project while using visual studio 2008, I got this error. In my this .aspx page I am using JSON (JavaScript Object Notation) and for JSON to work properly I was using System.Web.Services namespace.


I am giving all these details because I was not getting such error when I tried to run any of my .aspx webpage that was not using JSON technology. So lets have a look over how to solve this problem.


You just have to install .NET Framework 3.5 Service Pack and that's it. You can download the .NET Framework 3.5 Service Pack 1 microsoft website using this link http://www.microsoft.com/downloads/details.aspx?FamilyID=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en


If you found this link broken then go to google.com and search Download .NET Framework 3.5 Service Pack


Note:- In this example i am getting error about version 3.5.0.0 that's why i am installing .Net framework version 3.5. Check your framework version mentioned in error.


So this is the way to get rid of this Could not load file or assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. nasty error.
Read more...

Delete multiple rows in a gridview in asp.net using c#

In this asp.net tutorial you will learn how to delete multiple rows in gridview in asp.net using c#. During web development in number of occasions you may get requirement to delete the multiple rows in a gridview. In asp.net it is not difficult. Let's have a look over how to do so.

Delete multiple rows from gridview in asp.net using c#


.aspx


<asp:gridview id="GridView1" runat="server" width="100%">

<Columns>

<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:CheckBox ID="chkid" runat="server" Text='<%# Bind("User_ID")%>' />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Email" >
<ItemTemplate>
<asp:Label ID="lbl_Email" Text='<%# Bind("User_Email")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>

<asp:TemplateField HeaderText="First Name" >
<ItemTemplate>
<asp:Label ID="lbl_first_name" Text='<%# Bind("User_First_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Last Name" >
<ItemTemplate>
<asp:Label ID="lbl_last_name" Text='<%# Bind("User_Last_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>

</Columns>

</asp:gridview>


.aspx.cs


protected void Button1_Click(object sender, EventArgs e)
{

foreach(GridViewRow row in GridView1.Rows)
{
                  CheckBox chkbox = (CheckBox)row.FindControl("chkid");
                  string uid = chkbox.Text;
                  if (chkbox.Checked)
                  {


                   con.ConnectionString=strcon;
                   com.Connection=con;
                   con.Open();
                   string query = "Delete from users where User_ID='"+uid+"'";
                   com.CommandText = query;
                   com.ExecuteNonQuery();
                   con.Close();
                  fillgrid();

               }
}

}



Now let's first understand the code written in .aspx page.

I just put a gridview control in my aspx page just like the tutorial I have written to Displaying data from database in gridview. The only difference is that in very first <asp:TemplateField> I put a checkbox inside its <ItemTemplate> and give the checkbox User_ID as a Text which is the primary key in my users table. It is very much compulsory to provide unique/primary key to the checkbox so that deletion of multiple rows can be achieved without any problem. And then in the end, just below the gridview control I put the asp:button and using its server side onClick event I have written the code to delete the multiple rows in a gridview.

In above code snippet I am using the foreach loop which simply goes to each row of the gridview and then check whether the checkbox of that row is checked or not, if the checkbox of that row is checked then it will simply delete that row.

In the last I made call to the fillgrid() function to display the remaining records in gridview after deletion process. As I have already written this fillgrid() function in my previous tutorial Displaying data from database in gridview that's why in this post i avoid extra code. So That's it

Happy Coding!!!

Read more...

Redirection after some time delay in asp.net using c#

In this tutorial you will learn how to redirect user after some time delay in asp.net using c#. Normally people use redirection process after showing some message to their users, for example a message can be "Thank you for visiting our website" or after getting feedback from user you can display a message "Thank you for providing us your valuable feedback" and then redirect user to another page. It's just up to you in which scenario you want to use it. In asp.net normally we have three options to redirect user after some time delay.
1) Use javascript code in your c# code
2) Use Meta tag in your c# code
3) Use Response.AddHeader().

Redirection after some time delay in asp.net using c#

Let's have a look over these methods

1) Use javascript function in your c# code.
I have already written a post related how to write and execute the javascript code from c# code behind. You just have to put your javascript code in c# code behind and that's it. Let’s have a look over example given below

Yourpage1.aspx

<asp:Button ID="btnRedirect" runat="server" Text="Redirect" OnClick="btnRedirect_Click" />
In my .aspx page I have an asp:button control and using it’s onClick event I am redirecting user.

Yourpage1.aspx.cs
protected void btnRedirect_Click(object sender, EventArgs e)
{
string redirectionScript = "<script language='javascript'>" +
"function Delayer(){"+
"setTimeout('Redirection()', 5000);"+
"}"+
"function Redirection(){" +
"window.location = 'yourpage2.aspx';" +
"}" +
"Delayer()" +
"</script>";
Page.RegisterStartupScript("Startup", redirectionScript);
} 
It will redirect user to yourpage2.aspx after 5 seconds
 

2) Use meta tag in your c# code
I have already written a post for Implementing meta tags with master page in asp.net using c#. Let’s have a look over how to redirect user after some time delay by using meta tag in c# code behind.
protected void btnRedirect_Click(object sender, EventArgs e)
{
HtmlMeta equiv = new HtmlMeta();
equiv.HttpEquiv = "refresh";
equiv.Content = "5; url= yourpage2.aspx";
Header.Controls.Add(equiv);
}
OR
protected void btnRedirect_Click(object sender, EventArgs e)
{
Page.Header.Controls.Add(new LiteralControl("<meta http-equiv='refresh' content='5; url=yourpage2.aspx'/>"));
} 

It will redirect user to yourpage2.aspx after 5 seconds.

3) Use Response.AddHeader()


Use c# built-in method AddHeader() of Response Class to redirect user after some time delay. Let's have a look over how to do so

protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.AddHeader("REFRESH", "5;URL=yourpage2.aspx");
}

It will redirect user to yourpage2.aspx after 5 seconds.


This AddHeader()
function takes two Parameters. First one is HeaderName which is a string indicating the name of the new header. The second parameter is HeaderValue which is a string that indicates the initial value of the new header. It doesn't return any value.

So that's it.



Happy Coding
Read more...

How to restrict special characters being entered in textbox using javascript?

In this tutorial you will learn how to restrict the special characters being entered in textbox. Sometimes you want to restrict some special characters being entered in textbox of form to prevent the sql injection that can harm your database very badly. So Let's have a look over how to do so.


How to restrict special characters being entered in textbox using javascript?


<script language="javascript" type="text/javascript">
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event)
{
keynum = e.keyCode
}
// For Netscape/Firefox/Opera
else if (e.which)
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`")
{

return false;
}
else {
return true;
}
}
</script>

Now let's have a look over how to call this special characters restriction function in a textbox.

For aspx server side textbox control
<asp:TextBox ID="txtName" runat="server" onkeypress="return check(event)" ></asp:TextBox>

For html textbox control
<input type="text" name="txtName" id="txtName" onkeypress="return check(event)">

You can restrict any other character or number other than special characters too, just by simply add it in the list of characters to be restricted such as for example I want to restrict the character a too then the code will be
if (keychar == "'" || keychar == "`" || keychar == "a")

So this is the way to handle and restrict the special characters being entered in textbox using javascript.

Keep Coding…

Read more...

Learn how to write and execute the javascript code from c# code behind

In this tutorial you will learn how to write and execute the javascript code from c# code behind. Sometimes you may want to execute the javascript code directly from c# code behind. For example, you want to do so when a condition matches in your c# code like this
string name;
string std_name;

if(name==std_name)
{
//Now here you want to execute your javascript code
}

Learn how to write and execute the javascript code from c# code behind


In my .aspx page I am using a <span id="showMessage">and <asp:button>. When you will click the <asp:button>, focus will go to the server side then there I have written my code that will alert a message and display my name in the <span id="showMessage">. Let’s have a look over how to do so
protected void submit_Click(object sender, EventArgs e)
{

string popupScript = "<script language='javascript'>" +
"function GetAlert(){" +
"document.getElementById('showMessage').innerHTML = 'Adeel Fakhar';" +
"alert('Function is being called');" +
"}" +
"GetAlert()" +
"</script>";
Page.RegisterStartupScript("Startup", popupScript);
}

Page.RegisterStartupScript is used for registering and executing the client side script. This method takes two parameters. First one is key of type System.String and it acts as a unique key that identifies a script block. Second parameter is script which type is also System.String, it is content of script that will be sent to the client, means it contains your javascript code.

Page.RegisterStartupScript automatically attach the script just before the closing tag of your aspx page object’s <form runat="server">
element.

Page.RegisterStartupScript method uses a unique key to identify the script block; the script block does not have to be emitted to the output stream every time it is requested by a different server control instance.

Any script block with the same key parameter values is considered duplicate. You must remember to include HTML Comment Tags around your script so that it will not be rendered if the requesting browser does not support javascript.

So this is the way to write and execute the javascript code from c# code behind.
Read more...

How to fire the client side onclick() event of asp radio button?

In this tutorial you will learn how to fire the client side onclick() event of asp radio button. Using same technique you can fire the onclick() event of asp textbox, asp button, etc too. It is not a big deal. Let's have a look over how to do so.

How to fire the client side onclick() event of asp radio button?


The method to do this is very simple, you just have to write the
onclick="yourjavascriptfunction();"
and that’s it.

One thing remember that the intelliSense of visual studio will not show you the onClick() event in the list of available events for asp radio button when you will press the spacebar but you have to write this yourself in order to execute your javascript code using client side onclick() event of asp radio button because when your aspx page is rendered then asp radio button will become input radio button.

Now let's have a look over the complete example of the topic that we are discussing.

Home.aspx

<script language="javascript" type="text/javascript">
function ShowAlert()
{

alert("client side onClick event of asp radio button has been fired");

}
</script>
<table cellpadding="0" cellspacing="2" border="0" width="100%">
<tr>
<td width="28%">First Name:</td><td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Last Name:</td><td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Do you want to join us?</td><td><asp:RadioButton ID="rdoYes" runat="server" GroupName="Group1"
Text="Yes" onclick="ShowAlert();"/> <asp:RadioButton ID="rdoNo" runat="server" GroupName="Group1" Text="No"  onclick="ShowAlert();"/></td>
</tr>
</table>
So that's it. I hope you will find this tutorial very informative.
Read more...

Format the Phone Number in asp.net using c#

In this tutorial you will learn how to format the phone number entered in a textbox. Phone number can be entered in a textbox as 1234567890 but you can format it as (123)456-789 and this is our topic.

Let's have a look how to do so.


Format the Phone Number in asp.net using c#

Let's suppose we have an asp:textbox in our .aspx page in which user will enter the phone number. The id of asp:textbox is txtPhoneNumber.

public string PhoneNoFormation()
{
string formatedPhoneNo;
if (!string.IsNullOrEmpty(txtPhoneNumber.Text.ToString()) && txtPhoneNumber.Text.Length == 10)
{
string Phone1 = "(" + txtPhoneNumber. Text.Substring(0, 3) + ")";
string Phone2 = " " + txtPhoneNumber. Text.Substring(3, 3);
string Phone3 = "-" + txtPhoneNumber. Text.Substring(6, 4);
formatedPhoneNo = Phone1 + Phone2 + Phone3;
}

else
{
formatedPhoneNo = txtPhoneNumber.Text;
}

return formatedPhoneNo;
}

Now your phone number is in formatted form and you can save it in database if you want to do so.

So that's it. I hope you will find this tutorial very informative.

I love your feedback.

Read more...

How to add javascript file and css stylesheet dynamically to the header of the page in asp.net using c#?

In this tutorial you will learn how to add the javascript files and css stylesheets dynamically to the header of asp.net page inheriting masterpage using c#. Let's Suppose you have added a new module in your website inside a new folder, the folder name is NewModule. This module has its own css stylesheet and javascript files that will be attached to the more than 100 aspx webpages in it.

Now we have to add the javascript file and stylesheet to all these webpages of NewModule Dynamically. It’s not better approach to add these javascript file and css stylesheet to the masterpage and when these webpages of NewModule will be rendered then these javascript files and stylesheet will be automatically attached to the webpages located inside the NewModule folder. The reason why this approach is not good because the javascript file and stylesheet will be automatically attached to all those webpages other than NewModule folder that inherits from masterpage.

So let’s have a look example below that will cover the scenario that i discuss above.

How to add javascript file and css stylesheet dynamically to the header of the page in asp.net using c#?

Yourmasterpage.master.cs
protected override void OnPreRender(EventArgs e)
{
if (Request.RawUrl.ToLower().Contains("/newmodule /"))
{
LinkCss(); //It will Add CSS to Header
LinkJs(); //It will Add javascript to header
}
base.OnPreRender(e);
}
protected void LinkJs()
{
HtmlHead head = (HtmlHead)Page.Header;
HtmlGenericControl js = new HtmlGenericControl("script");
js.Attributes.Add("type", "text/javascript");
js.Attributes.Add("language", "javascript");
js.Attributes.Add("src", Page.ResolveUrl("~/js/yourjsfile.js"));
head.Controls.Add(js);
}
protected void LinkCss()
{
HtmlHead head = (HtmlHead)Page.Header;
HtmlLink css = new HtmlLink();
css.Attributes.Add("href", Page.ResolveUrl("~/styles/yourstylesheet.css"));
css.Attributes.Add("type","text/css");
css.Attributes.Add("rel","stylesheet");
head.Controls.Add(css);
}

Now let’s understand the code.

First of all in OnPreRender(EventArgs e) event of masterpage, I am checking whether the url in the address bar contains the NewModule flder name(the folder containing all the new developed webpages in which I want to add the javascript and stylesheet dynamically) using Request.RawUrl, if it contains the NewModule folder name then the LinkCss() and LinkJs() functions will get call and javascript file and css stylesheet will be attached to the aspx webpages dynamically. You can call LinkJs() and LinkCss functions in the page_load() function of your masterpage too.

So that's it. I hope you will find this tutorial very informative.

I love your feedback.
Read more...

How to Specify Multiple Actions from Single Form Using Javascript?


In this programming tutorial we will learn how to specify multiple actions from single form using javascript. As we all know that there is always one submit button available in one form, so if you want to submit your form to multiple Web Pages then you have to use input buttons instead of submit button and javascript code for this purpose.
How to Specify Multiple Actions from Single Form Using Javascript?

Lets have a look over the example given below.
yourpage.php

<html>
<head>
<title>Specify Multiple Actions From Single Form</title>
<script language="javascript" type="text/javascript">
function FuncButton1()
{
document.form1.action = "Page1.php" //Sets the action attribute of the form
document.form1.submit(); // Submit the page
return true;
}

function FuncButton2()
{
document.form1.action = "Page2.php" //Sets the action attribute of the form
document.form1.submit(); // Submit the page
return true;
}

</script>
</head>

<body>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<form name="form1" method="post">
<tr>
<td>First Name</td><td><input type="text" id="txt_Firstname" name="txt_Firstname"/></td>
</tr>
<tr>
<td>Last Name</td><td><input type="text" id="txt_Lastname" name="txt_Lastname"/></td>
</tr>
<tr>
<td>Email</td><td><input type="text" id="txt_Email" name="txt_Email"/></td>
</tr>
<tr>
<td>Username</td><td><input type="text" id="txt_Username" name="txt_Username"/></td>
</tr>
<tr>
<td><input type="button" value="Button1" onClick="return FuncButton1();" /></td><td><input type="button" value="Button2" onClick="return FuncButton2();"/></td>
</tr>
</form>
</tr>
</table>
</body>
</html>
Now lets understand.

First of all I have created a simple html form with two noticeable things. First noticeable thing is that there is no submit (type="submit") button in the form and secondly I have not set any action attribute of the form.

To post the data to two different web pages I have created two input buttons and using onClick event of these buttons I am setting the "action" of the form dynamically and then submit the form. So whenever user clicks the Button1 then the Page1.php will be called and whenever user clicks the Button2 then the Page2.php will be called.

So that's it. I love your feedback
Read more...

Getting file extension in php

In this php tutorial you will learn how to get the file extension from a string in php. Sometimes during web development you may need to get the file extension, so let's have a look over how to do this.

There are different ways to do this. Let's have a look over each of them


1) Using explode()

The simplest and easiest way of getting file extension is to use the php built-in function explode.

The explode() function breaks a string into an array.

It takes three parameters in which two of them are required and one is optional.

a) The first required parameter is separator that specifies where to break the string.
b) The second required parameter is string that specifies the string to split.
c) The optional parameter is limit that specifies the maximum number of array elements to return.

So let's have a look over how to get the file extension using explode() method.

<?php
$filename="picture.jpg";
$fileArray=array();
$fileArray =explode('.',$filename);
$file_extension=$fileArray[1];
echo $file_extension;
?>


or you can made a custom php function and call explode() method in it and in the end return the value

<?php
function get_file_extension($file_name)
{
return end(explode('.',$file_name));
}


$filename="picture.jpg";
$file_extension=get_file_extension($filename);
echo $file_extension;
?>

2) Using PATHINFO_EXTENSION

Another way to get the file extension is to use the pathinfo which is an array that contains dirname, basename, extension and file name. Right now we are only interested in the file extension so I am going to call it directly.

<?php
$filename="picture.jpg";
$file_extension = pathinfo($filename,PATHINFO_EXTENSION);
echo $file_extension;
?>


Or you can do like this

<?php
function get_file_extension($file_name)
{
return pathinfo($file_name, PATHINFO_EXTENSION);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

3) Using substring and string char

You can use substring and string char to determine the file name length and position to get the file extension. Let’s have a look over how to do this

<?php
function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

So these are the different ways to get the file extension in php.
Read more...

Redirection in javascript after some time delay

In this programming tutorial we will learn how to redirect the user to another web page or website after some time delay. Its quite easy in javascript as you have to write just single line of code. Lets have a look over the example given below.
Redirection in javascript after some time delay
For this purpose there is a built-in javascript method setTimeout().
setTimeout() method is used to repeatedly call some function after a specified amount of time.

Syntax of setTimeout() Method
setTimeout("Javascript Statement",Milliseconds);

Note: - The setTimeout() is the method of the HTML DOM Window object.

setTimeout() method takes two parameters. The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('2 seconds!')" or a call to a function, like "helloMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first parameter.

Note: - There are 1000 milliseconds in one second.

So lets have a look over the code
<html>
<head>
<title>Redirection in javascript after some time delay</title>
<script language="javascript" type="text/javascript">
function Delayer()
{
setTimeout('Redirection()', 5000);
}
function Redirection()
{
window.location="http://www.google.com";
}
</script>
</head>
<body>
<form>
<input type="button" value="Redirect after 5 secs" onclick="Delayer();" /></form>
</body>
</html>
The above mentioned code will redirect user to the google.com after 5 seconds of clicking the button. When user will click the button, the function Delayer() will be get call and in this function I am calling Redirection() function after every 5 seconds. So when focus will move to the Redirection() function after every 5 seconds then the user will be immediately redirected to the google.com

So that's it.
I love your feedback.
Read more...

How to disable the browser back button

In this javascript tutorial you will learn how to disable the back button on FireFox's browser or how to prevent the user to go back in FireFox’s browser. Although I am giving force to FireFox's browser yet this code works for all web browsers such as Google Chrome, Opera, Safari, Internet Explorer etc. The reason why I am giving force over FireFox because it is even hard in FireFox to disable the back button or to prevent user to go back.

For example, the below mentioned code will work in other web browsers such as Internet Explorer, Google Chrome but will not perform his responsibility incase of FireFox.


<script language="javascript" type="text/javascript">
window.history.forward(1);
</script>

Also this code will work in other browsers but in case of FireFox it will not work
<script language="javascript" type="text/javascript">
if(history.back)
{
history.go(+1)
}
</script>

So now let's have a look over javascript code that will disable the back button and prevent user to go back in Firefox and in all other browsers

<script language="javascript" type="text/javascript">
function noBack()
{
window.history.forward()
}
noBack();
window.inhibited_load=noBack;
window.onpageshow=function(evt){if(evt.persisted)noBack()}
window.inhibited_unload=function(){void(0)}
</script>

So this is the way to disable the back button on firefox and prevent user to go back.
Read more...

Trim() function in javascript

In this javascript tutorial you will learn how to remove whitespace before /after the string using trim() function in javascript.

Let's have a look over below mentioned javascript custom function that will remove whitespace before/after the string.

function TrimString(str)

{

return str.replace(/^\s+|\s+$/g,"");

}

The calling of this function is very simple, you just have to provide string argument to this function.

I have developed an html web page in which I have a custom function for Trimming which is TrimString() and to call this TrimString() function I have made another function TrimMyString() and I am calling this TrimMyString() function via onclick event of hyperlink.

In this function first of all I declared a variable Myname and assign a string value to it but one thing must be noticed that there are some whitespace before/after the string value and then I calculate the length of that string and store the length in another variable len and then alert the length of the string before the trimming process. After this I used the function TrimString() to trim the string so that whitespace before/after string value can be removed and then again I calculate the length of string after trimming and then alert the length.

Now this time you will find the huge difference between two lengths before and after the trimming process and that difference will tell you how effective and efficient this simple javascript custom function is. Actually this custom function is using regular expression for trimming the whitespace before/after the string, means this function is capable of both ltrim and rtrim.

<html>

<head>

<title>Trim() function in javascript</title>

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

function TrimString(str)

{

return str.replace(/^\s+|\s+$/g,"");

}

function TrimMyString()

{

var Myname,len;

Myname=" Adeel Fakhar ";

len=Myname.length;

alert(len);

Myname=TrimString(Myname);

len=Myname.length;

alert(len);

}

</script>

</head>

<body>

<a href="javascript:TrimMyString();" > Call Trim function</a>

</body>

</html>

So this is the way to trim the string in javascript using trim() function.

Read more...

Passing QueryString from asp.net hyperlink in asp.net using c#

In this asp.net tutorial you will learn how to pass QueryString from asp.net hyperlink in asp.net using c#. Let's have a look over how to do this. In first example we will look how to pass single QueryString from asp.net hyperlink and then in second example we will look how to pass multiple QueryString params from asp.net hyperlink.

First Example:-

<asp:TemplateField HeaderText="Case No">

<ItemTemplate>

<asp:HyperLink ID="hyp_Caseno" Text='<%# Bind("Case_No")%>' runat="server" NavigateUrl='<%# "yourpage.aspx?caseno=" + DataBinder.Eval(Container.DataItem,"Case_No")%>'></asp:HyperLink>

</ItemTemplate>

</asp:TemplateField>

Note:- The Case_No in DataBinder.Eval is the column name of your database’s table. Actually we are getting values of the column from database’s table whenever grid will bind.

Now let’s have a look over how to pass multiple QueryString Params from asp.net hyperlink

Second Example:-

<asp:TemplateField HeaderText="Case No">

<ItemTemplate>

<asp:Hyperlink ID="hyp_Caseno" Text='<%# Bind("Case_No")%>' runat="server" NavigateUrl='<%# "yourpage.aspx?caseno=" + DataBinder.Eval(Container.DataItem,"Case_No") + "&productid=" + DataBinder.Eval(Container.DataItem,"Product_ID")%>' />

</ItemTemplate>

</asp:TemplateField>

So this is the way to pass single and multiple QueryString params from asp.net hyperlink.

Happy Coding

Keep Coding

Read more...

How to fire onClick event of LinkButton inside gridview in asp.net using c#

In this asp.net tutorial you will learn how to fire onclick event of LinkButton inside gridview in asp.net using c#. Normally you can't fire the onclick event of LinkButton which lies inside gridview but in this tutorial we will look how to do this.

Let's have a look over .aspx page in which we have gridview control

.aspx page

<asp:gridview ID="GridView1" runat="server" Width="100%" EnableTheming="false" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Customer ID">

<ItemTemplate>

<asp:LinkButton ID="lnk_CustomerID" Text='<%# Bind("Customer_ID")%>' runat="server" OnClick="lnk_CustomerID_Click"></asp:LinkButton>

</ItemTemplate>


</asp:TemplateField>

<asp:TemplateField HeaderText="Customer Name">

<ItemTemplate>

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

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Customer Age">

<ItemTemplate>

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

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:gridview>

As you can see that I have Link button inside the gridview that in mycase contains the unique values which is Customer ID. Now I want to fire the onclick event of LinkButton to execute some other code, which is to store the Text of LinkButton in a session and then want redirection to the Customer Detail page. Let’s have a look how it can be done.

.cs page

protected void lnk_CustomerID_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
GridViewRow gv = (GridViewRow)(link.Parent.Parent);
LinkButton CustomerID = (LinkButton)gv.FindControl("lnk_CustomerID");
Session["customerid"] = CustomerID.Text;
Response.Redirect("customer_detail.aspx");
}
So this is the way to fire the onclick event of LinkButton inside gridview in asp.net using c#.

Happy Coding...!

Keep Coding...!
Read more...

Highlight gridview row on mouse over using javascript and css in asp.net using c#

In this asp.net tutorial you will learn how to highlight gridview row on mouse over using javascript and css in asp.net using c#. There are couples of methods to highlight rows of gridview on mouse over. I preferred first one which is OnRowDataBound event of GridView.

So let's have a look over .aspx code


Highlight_gridview_row.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="highlight_gridview_row.aspx.cs" Inherits="MainFolder_SubFolder_highlight_gridview_row" %>

<!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 runat="server">
<title>Highlighting gridview row on mouse over using css and javascript in asp.net and c#</title>
<style type="text/css">
.highlightrow
{
background-color:#e5e5e5;
}
.normal
{
background-color:white;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview id="GridView1" runat="server" width="100%" EnableTheming="false" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Email" >
<ItemTemplate>
<asp:Label ID="lbl_Email" Text='<%# Bind("User_Email")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" >
<ItemTemplate>
<asp:Label ID="lbl_first_name" Text='<%# Bind("User_First_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" >
<ItemTemplate>
<asp:Label ID="lbl_last_name" CssClass="aLinkButton" Text='<%# Bind("User_Last_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Label ID="lbl_RecordNotFound" Text="No Record Found" runat="server" Font-Size="Larger" ForeColor="maroon" ></asp:Label>
</EmptyDataTemplate>
</asp:gridview>

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

I have created two internal css classes that will play their role for highlighting the rows of gridview, these are

.highlightrow
{
background-color:#e5e5e5;
}
.normal
{
background-color:white;
}

I will call highlightrow class for onmouseover client side event and second class for onmouseout client side event.


Highlight_gridview_row.aspx.cs

First Method:-

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='highlightrow'"); e.Row.Attributes.Add("onmouseout", "this.className='normal'");

}
}

Or you can do this without defining internal css classes in this way

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#e5e5e5'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#ffffff'");
}
}


Second Method:-

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='highlightrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normal'");
}

}

Once again I m saying that I prefer First Method which is to highlight gridview row on mouse over by using OnRowDataBound event because why should we create the OnRowCreated event of Gridview, if we can do this work in OnRowDataBound event. One thing more, the code written in Second Method can also run without OnRowCreated event of Gridview but once again why should we write extra function, if we we can write that code in OnRowDataBound event of gridview.

So these are the ways to highlight gridview row on mouse over using css and javascript in asp.net using c#.

Happy Coding…..

Keep Coding…….
Read more...

PHP performance tips and tricks

In this php tutorial we will learn different PHP performance tips and tricks that will enhance the performance of development using php.

1) Don't use varaibles when there is no need of them

Most of the times the php developer try to clean his/her code by assigning the values of predefined variables to the variable created by him/her of shorter name. This can also become the way of better understanding of php code but it double consume the memory without any need becuase first you will declare the variable and then you will assign the values of predefined variables to those custom variables. Let's have a look over the example to better understand what i mean.

Wrong
$comments=$_POST['comments'];
echo $comments;

Correct
echo $_POST['comments'];

In the above example if the malicious user had inserted the spam text in the comments textarea of 512KB worth of characters then it would use the memory of 1MB without any need.

2) Make habit to Use single-quotes for strings

In PHP you can use both single and double-quotes for string variables but there are some differences between both of them. Using double-quotes for strings tell the engine of php to first read the content of string and then look for variables and then replace variables with their values. So if the string contains no variable then please use single-quote instead of double-quote. Let's have a look over the example

Wrong
$name="My name is Adeel Fakhar";

Correct
$name='My name is Adeel Fakhar';

It is better to use concatenation then double-quotes for string. Let's have a look over the example

Wrong
$name='Adeel Fakhar';
$myname="My name is $name";

Correct
$name='Adeel Fakhar';
$myname='My name is'.$name.' Ok';

Make habit to use echo to print

Use echo to print the results in better readability and better performance.

Wrong
print $name;

Correct
echo $name;

I will also write a post for difference between echo and print.

Don't try to use the concatenation with echo

Most of the novice php programmers don't know that they can pass multiple variables to the echo, seprating with commas, instead of concatenating them first.

Wrong
$firstname='Adeel';
$lastname='Fakhar';

echo 'My name is'.$firstname.$lastname.' OK my dear';

Correct
$firstname='Adeel';
$lastname='Fakhar';

echo 'My name is',$firstname,$lastname,' OK my dear';

Try to use switch/case instead of if/else

If there is a single variable in your php code for comparison purpose then please try to use switch/case instead of if/else for better performance and readability. Let's have a look over the example

Wrong

if($_POST['action'] == 'sum')

{

sumFunction();
}

elseif ($_POST['action'] == 'sub')

{
subFunction ();
}

elseif ($_POST['action'] == 'mul')

{
mulFunction ();
}

else {
defaultFunction();
}

Correct
switch($_POST['action'])

{
case 'sum':
sumFunction();
break;


case 'sub':
subFunction ();
break;


case 'mul':
mulFunction ();
break;


default:
defaultFunction();
break;
}

It’s my suggestion to first understand the language, clear your logic then apply these above mentioned steps,techniques,tips and tricks, what ever you say to enhance the performance of your development. As you have seen that the tutorials I have written in my blog, I haven’t follow any of these techniques because my purpose was to solve your problem quickly rather than to teach you how to write code but in professional coding life you must follow these steps in order to enhance your development performance.

If you like this post of PHP performance tips and tricks then you must thankful to code.google.com because I have read these performance enhancement techniques there and then I decided to write a post for this on my blog.

Happy Coding….. Keep Coding


Read more...