Tuesday 24 September 2013

How to show the message in asp.net website using javascript.

In this article , I have explained how to show Message Box in asp.net website using javascript.I will also tell you how to solve error Message Box not working inside update panel. Message box is frequently used in asp.net application for showing the message.

In the code behind file(.aspx.cs ) write the below code:-

protected void btnSave_Click(object sender, EventArgs e)
    {

   ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Data Submitted Successfully');", true);

    }

If you are using Update panel then this code will not work.So please write the below code in code behind page.

protected void btnSave_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Data Submitted Successfully');", true);

    }

Wednesday 18 September 2013

Fetch random rows from database(Oracle,MySql,MS Sql).

In this article, I have explained how to fetch random rows from database (Oracle,MySql,Ms Sql).
This is usefull when you have to show random information like articles,pages,links to user.There are various way to fetch random rows from table.But here I have show you in easy way to do from sql.

Oracle:-

SELECT column FROM
(
SELECT column FROM Table
ORDER BY dbms_random.value
)
WHERE rownum <= 10;

MySql:-

SELECT column FROM table
ORDER BY RAND()
LIMIT 10;

MS Sql:-


SELECT top 1 * FROM Employee_Demo ORDER BY NEWID();

Delete ,Truncate and Drop command in Sql.

DELETE :-
Delete statement is used to delete rows form table.

Syntax:-
DELETE FROM table [WHERE_CONDITION]

Note:- Here where clause  is optional.If you do not include in the query then it will delete all the rows from the table. If you want to delete some particular row or rows the you have to include where clause in the query.So be careful while deleting the data from table.
If you want to delete single row from the table for employee having id=100, then use below query.
DELETE FROM employee WHERE id=100;

To delete all rows from employee table, the query would be like

DELETE FROM employee;

Truncate:-
Truncate command is used to delete  all the rows from the table and free the space conating table.
Syntax:-
TRUNCATE TABLE table_name;

Example:-
If you want to delete the records from the Employee table , the query would like this.
TRUNCATE TABLE Employee;

Drop:-
Sql Drop command is used to remove an object from the database. If you want to drop a table, all the rows in the table are deleted and the table structure is removed from the database. Once a table is dropped
we cannot get it back means roll back is not possible in DROP.

Syntax :-
DROP TABLE table_name;

Example:- Drop the employee table, the query would like this


DROP TABLE Employee;

Difference between Delete ,Truncate and Drop command in Sql.

Delete:-

Delete command delete all the rows from the table if you exclude where condition or delete some row from the table if you include where condition.
It does not free the space containing the table.
Use all delete trigger on the table to fire.
It deallocate row by row log transaction so that it is slower that truncate.
Roll back is possible if you use inside transaction.

Truncate:-

Truncate command is used to delete  all the rows from the table .
free the space containing table.
No where clause is used.
No triggers are fired on this operation because no individual log row used.
Roll back is possible if you use inside transaction.

DROP:-


If table is dropped , all the relationships with the tables will no longer be available, the index,triggers,constraint and permission specifications also dropped. If you want to use the table again  it has to be created again with all the thing you required.

Tuesday 17 September 2013

ViewState in Asp.Net.

In classic Asp ,when form is submitted , all form values are cleared. If you have filled lot of values in the form and submitted and due to some reason an error come from server. Then at that time you have to fill the form again with all the necessary data. When you click the button form is submitted and all the fields are clear automatically.
If you again fill the form with some minor changes then again you have to fill all the fields.
But in Asp.Net , when you submit the form with all values and form is post back then values are remain on the field. How this is possible. This is possible because of ViewState. ViewState store the value in hidden form in the web page. ViewState allows Asp.Net to repopulate form fields on each postback to server.
ViewSate values are not carried between pages. If you want to carries values between pages then you have to use cookies or session because cookies or session can be accessed from all your pages on your websites.
Let’s take example to see how ViewState works.

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Submit & set Name"
            onclick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="Refresh"
            onclick="Button2_Click" /><br />
        Retrieve from ViewState :<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>   
    </form>
</body>
</html>

Run the form and see the out. On the label the value is Not Set.........
Fill the textbox and click the first button. Then you will the label value also change. Now click on second button and then you will see again label value has not change.
Clear the text value and click the second button. Then you will see the label contain the same value what you have enter in the textbox.

If you want to store more complex value or huge amount of data to use across the page or website then it’s better to use session or cookies.
ViewState is not secure for transferring the private data across the pages or website because it can be easily hack.

By default viewstate is enable in asp.net. You can enable or disable according to you requirement. You can enable or disable viewstate for whole page or some particular control.

If you want to enable viewsate for whole page then write the in design page just like as.

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

For particular control :-


TextBox1.EnableViewState = true;

Validate Asp.Net checkbox list using Custom validator .

In this article , I have explained how to validate Asp.net checkboxlist using custom validator means I have to select atleast one checkbox from checkboxlist.

Put the checkboxlist control on design page and add some items in it and one cutome validator and one button.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Text="c#"></asp:ListItem>
    <asp:ListItem Text="ASP"></asp:ListItem>
    <asp:ListItem Text="Asp.Net"></asp:ListItem>
    <asp:ListItem Text="Sql"></asp:ListItem>
    <asp:ListItem Text="Ajax"></asp:ListItem>
    </asp:CheckBoxList>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select atleast one item from list." ForeColor="Red"
    ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator>
    <asp:Button ID="Button1" runat="server" Text="Submit" />

JavaScript Function:-

Here I have written javascript function for selecting atleast one checkbox from checkboxlist and called this method on custom validator.
This function is executed when cutom validator is trigered on button click.
If checkbox is checked then isvalid value set to true else false.

<script type="text/javascript">
    function ValidateCheckBoxList(sender, args) {
    var checkBoxList=document.getElementById("<%=CheckBoxList1.ClientID %>");
    var checkBox=document.getElementsByTagName("input");
    var isvalid=false;
    for(var i=0;i<checkBox.length;i++)
    {
        if (checkBox[i].checked) {
            isvalid = true;
            break;
        }
    }
    args.IsValid = isvalid;
    }

</script>


Sunday 15 September 2013

How to select only one radio button from two or more radio buttons without writing any code in Asp.Net.

In this article, I have explained how to select only one radio button from multiple radio buttons without writing any code in asp.net. It’s very easy to select single radio button from multiple radio buttons. Let’s take an example.

Put two radio buttons control on design page. Select the first radio button and go to the properties of that radio button and give a name to Group Name. I have given group name as one (you can give group name according to your requirement).

<asp:RadioButton ID="RadioButton1" runat="server" GroupName="one" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="one" />

GroupName property to specify a grouping of radio buttons to create a mutually exclusive set of controls. You can use the GroupName propery to select single radio button from multiple selection option from radio buttons control.


The value of this property is stored in view state.

Friday 13 September 2013

How to delete duplicate record from the table in MS SQL.

In the previous article, I have explained how tofind duplicate records in the table in MS SQL.
In this article, I have explained how to delete duplicate records from the table in MS SQL.

First create a temporary table on which you can test.

Write the following query to create temporary table in MS SQL.

SELECT * INTO TempExamResult FROM ExamResult --TempExamResult is a name of temporary table which taking all data from ExamResult

Now you can play with this table freely.

Write the following query to find duplicate records in the table and delete it from the table.

WITH Duplicates AS
(
SELECT
     name,Marks,
     ROW_NUMBER() OVER( PARTITION BY Subject,name
          ORDER BY Subject,name DESC) AS Sus
FROM TempExamResult
)
DELETE Duplicates
WHERE Sus > 1


Now check the table records for surety that duplicate records deleted  from table or not.
After that drop temporary table.

How to find duplicate record in the table in MS Sql.

First we create a table without having any primery key.

Create table ExamResult(name varchar(50),Subject varchar(20),Marks int)

Now insert some dummy data into this table.
I have inserted 10 records in this table.

insert into ExamResult values('Adam','Maths',70)
insert into ExamResult values ('Adam','Science',80)
insert into ExamResult values ('Adam','Social',60)

insert into ExamResult values('Rak','Maths',60)
insert into ExamResult values ('Rak','Science',50)
insert into ExamResult values ('Rak','Social',70)

insert into ExamResult values('Sam','Maths',90)
insert into ExamResult values ('Sam','Science',90)
insert into ExamResult values ('Sam','Social',80)
insert into ExamResult values ('Sus','Bio',30)

Now it’s time to find Duplicate values in a table use of the following query with actual values.

SELECT name, COUNT(*) AS DupeCount
FROM ExamResult
GROUP BY name
HAVING COUNT(*) > 1

Second Method:-
If you find duplicate values and list of rows that contain them , use the following query.


SELECT * FROM ExamResult WHERE name  IN (SELECT name FROM ExamResult GROUP BY name HAVING COUNT(*)>1) ORDER BY name

Saturday 7 September 2013

Add two no’s using stored procedure in SQl SERVER 2008.

In this article, I have explained how to add two no’s using stored procedure in Sql server 2008.

Create procedure sp_addNo(@no1 int,@no2 int)
AS

BEGIN

declare @total int

SELECT (@no1+@no2) as total;


End

For Executing stored procedure :-

 exec sp_addNo 5,5

This will the output : 
total
10

Friday 6 September 2013

Validation using JQuery in Asp.Net.

In this article , I have explained validation using Jquery in Asp.net. Validation using jquery is better than JavaScript. For validation using JQuery I have used Jquery file. So first Download the required Jquery file which is attached in download code..

Now I have to design a page means put some control on page and write Jquery code.


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

<!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 id="Head1" runat="server">
<title>Show Inline validation Messages</title>
<link href="CSS/template.css" rel="stylesheet" type="text/css" />
<link href="CSS/validationEngine.jquery.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.6.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="Scripts/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#form1").validationEngine();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table align="center">
<tr>
<td colspan="2">
<div style="border: 1px solid #CCCCCC; padding: 10px;">
<table cellpadding="0" cellspacing="30" style=" background-color:White">
<tr>
<td>First Name:</td>
<td><asp:TextBox ID="txtfname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="TextBox1"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="txtlname"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><asp:TextBox ID="TextBox2"  runat="server" CssClass="validate[required]"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>

For validation of textbox , I have not use one by one id of textbox .Because I have to call every textbox id in jquery function. So it’s better to call form id which will pass all the form control id automatically.

When you will click on submit button ,it will show the error message. It will also show the error message when you pass the empty textbox.


Click here to download Code.