Sunday, February 5, 2012

Show or Hide Div using jquery

Show hide div using jquery example in asp.net.

So many times while developing web application we need to show or hide div or other html elements based on user interaction as shown in picture.

we can do this with ease using JQuery.








for this first of all we need to add jquery in head section of page.


1<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>

Now write some css for the div and show hide button

01.button, .button:visited {
02 background: #222;
03 display: inline-block;
04 padding: 5px 10px 6px;
05 color: #fff;
06 text-decoration: none;
07 -moz-border-radius: 6px;
08 -webkit-border-radius: 6px;
09 -moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
10 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
11 text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
12 border-bottom: 1px solid rgba(0,0,0,0.25);
13 font-size: 11px;font-weight: bold;line-height: 1;text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
14        background-color: #2981e4;
15        top:250px;
16        float:left;
17        left:150px;
18        position:fixed;
19 
20}
21.button:hover {background-color: #2575cf;}
22 
23.detailDiv {
24 height:80px;
25        width: 400px;
26 background: #222;
27 display: inline-block;
28 padding: 50px 10px 6px;
29 color: #fff;
30 text-decoration: none;
31 -moz-border-radius: 6px;
32 -webkit-border-radius: 6px;
33 -moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
34 -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
35 text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
36 border-bottom: 1px solid rgba(0,0,0,0.25);
37 position: relative;
38 cursor: pointer
39        font-size: 11px;font-weight: bold;line-height: 1;text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
40        background-color: #91bd09;
41 text-align:center;
42}
43.detailDiv:hover {background-color: #749a02;}


Write this html code to hide or show the div
<div class="detailDiv">
This is example of Hide show div element using jquery 
</div>

<button class="button">Show or Hide div </button>

Now we will be showing or hiding the div on click of button so we need to add click event listener in jquery function as follows.

01<script type="text/javascript">
02 
03$(document).ready(function(){
04 
05        $(".detailDiv").hide();
06        $('.button').click(function(){
07 $(".detailDiv").slideToggle();
08 });
09 
10});
11 
12</script>

And result will be like one in demo below, Click on button to see it live.








Have fun with JQuery
Export Gridview to excel
Export GridView to Excel in asp.net 2.0,3.5 using C# and VB.NET

In this post i am going to explian how to export gridview to ms excel using C# and VB.NET.

For this i have used northwind database to populate gridview. To learn how to populate gridview read this.





Read this post If you want to export gridview to pdf using iText.

After populating gridview we have to export gridview to excel on click of button placed in page.

For this we can simply write this code in click event of button

01Response.ClearContent();
02 
03        Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
04 
05        Response.ContentType = "application/excel";
06 
07        StringWriter sWriter = new StringWriter();
08 
09        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
10 
11        GridView1.RenderControl(hTextWriter);
12 
13        Response.Write(sWriter.ToString());
14 
15        Response.End();

httpexception error
But when we click on button to export gridview to excel we get this httpexception error.

to get past this either we can write this method in code behind.








1public override void VerifyRenderingInServerForm(Control control)
2{
3}

or we can add a html form and render it after adding gridview in it, i'll be using this.

RegisterForEventValidation error
If we have enabled paging in gridview or gridview contains controls like linkbutton, dropdowns or checkboxes etc then we get this error.

we can fix this error by setting event validation property to false in page directive.




1<%@ Page Language="C#" AutoEventWireup="true"  <b>EnableEventValidation="false" </b>CodeFile="Default.aspx.cs" Inherits="_Default" %>


When we export gridview containg controls then hyperlinks or other controls are not desireable in excel sheet, we need to display their display text insted for this we need to write a method to remove controls and display their respective text property as mentioned below.

01private void ChangeControlsToValue(Control gridView)
02    {
03        Literal literal = new Literal();
04 
05        for (int i = 0; i < gridView.Controls.Count; i++)
06        {
07            if (gridView.Controls[i].GetType() == typeof(LinkButton))
08            {
09 
10                literal.Text = (gridView.Controls[i] as LinkButton).Text;
11                gridView.Controls.Remove(gridView.Controls[i]);
12                gridView.Controls.AddAt(i,literal);
13            }
14            else if (gridView.Controls[i].GetType() == typeof(DropDownList))
15            {
16                literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;
17 
18                gridView.Controls.Remove(gridView.Controls[i]);
19 
20                gridView.Controls.AddAt(i,literal);
21 
22            }
23            else if (gridView.Controls[i].GetType() == typeof(CheckBox))
24            {
25                literal.Text = (gridView.Controls[i] as CheckBox).Checked ? "True" : "False";
26                gridView.Controls.Remove(gridView.Controls[i]);
27                gridView.Controls.AddAt(i,literal);
28            }
29            if (gridView.Controls[i].HasControls())
30            {
31 
32                ChangeControlsToValue(gridView.Controls[i]);
33 
34            }
35 
36        }
37 
38    }
Complete HTML source of page look like
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
              DataSourceID="sqlDataSourceGridView" 
              AutoGenerateColumns="False"
              CssClass="GridViewStyle" 
              GridLines="None" Width="650px" 
              ShowHeader="False">
<Columns>
<asp:TemplateField HeaderText="Customer ID" ItemStyle-Width="75px">
<ItemTemplate>
<asp:LinkButton ID="lButton" runat="server" Text='<%#Eval("CustomerID") %>' 
                PostBackUrl="~/Default.aspx">
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="75px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="Company" 
                ItemStyle-Width="200px" >
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ContactName" HeaderText="Name" 
                ItemStyle-Width="125px">
<ItemStyle Width="125px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="City" HeaderText="city" ItemStyle-Width="125px" >
<ItemStyle Width="125px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Country" HeaderText="Country" 
                ItemStyle-Width="125px" >
<ItemStyle Width="125px"></ItemStyle>
</asp:BoundField>
</Columns>
<RowStyle CssClass="RowStyle" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedRowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingRowStyle CssClass="AltRowStyle" />
</asp:GridView>

<asp:SqlDataSource ID="sqlDataSourceGridView" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], 
               [City], [Country] FROM [Customers]">
</asp:SqlDataSource>

<table align="left" class="style1">
<tr>
<td class="style2">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" 
                     RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem Value="0">All Pages</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:Button ID="btnExportToExcel" runat="server" Text="Export To Excel" 
            Width="215px" onclick="btnExportToExcel_Click"/>
</td>
</tr>
</table>
C# Code
01protected void btnExportToExcel_Click(object sender, EventArgs e)
02    {
03        if (RadioButtonList1.SelectedIndex == 0)
04        {
05            GridView1.ShowHeader = true;
06            GridView1.GridLines = GridLines.Both;
07            GridView1.AllowPaging = false;
08            GridView1.DataBind();
09        }
10        else
11        {
12            GridView1.ShowHeader = true;
13            GridView1.GridLines = GridLines.Both;
14            GridView1.PagerSettings.Visible = false;
15            GridView1.DataBind();
16        }
17 
18        ChangeControlsToValue(GridView1);
19        Response.ClearContent();
20 
21        Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
22 
23        Response.ContentType = "application/excel";
24 
25        StringWriter sWriter = new StringWriter();
26 
27        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
28 
29        HtmlForm hForm = new HtmlForm();
30 
31        GridView1.Parent.Controls.Add(hForm);
32 
33        hForm.Attributes["runat"] = "server";
34 
35        hForm.Controls.Add(GridView1);
36 
37        hForm.RenderControl(hTextWriter);
38 
39        Response.Write(sWriter.ToString());
40 
41        Response.End();
42    }
43 
44    private void ChangeControlsToValue(Control gridView)
45    {
46        Literal literal = new Literal();
47 
48        for (int i = 0; i < gridView.Controls.Count; i++)
49        {
50            if (gridView.Controls[i].GetType() == typeof(LinkButton))
51            {
52 
53                literal.Text = (gridView.Controls[i] as LinkButton).Text;
54                gridView.Controls.Remove(gridView.Controls[i]);
55                gridView.Controls.AddAt(i,literal);
56            }
57            else if (gridView.Controls[i].GetType() == typeof(DropDownList))
58            {
59                literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;
60 
61                gridView.Controls.Remove(gridView.Controls[i]);
62 
63                gridView.Controls.AddAt(i,literal);
64 
65            }
66            else if (gridView.Controls[i].GetType() == typeof(CheckBox))
67            {
68                literal.Text = (gridView.Controls[i] as CheckBox).Checked ? "True" : "False";
69                gridView.Controls.Remove(gridView.Controls[i]);
70                gridView.Controls.AddAt(i,literal);
71            }
72            if (gridView.Controls[i].HasControls())
73            {
74 
75                ChangeControlsToValue(gridView.Controls[i]);
76 
77            }
78 
79        }
80 
81    }
VB.NET CODE
01Protected Sub btnExportToExcel_Click(sender As Object, e As EventArgs)
02 If RadioButtonList1.SelectedIndex = 0 Then
03  GridView1.ShowHeader = True
04  GridView1.GridLines = GridLines.Both
05  GridView1.AllowPaging = False
06  GridView1.DataBind()
07 Else
08  GridView1.ShowHeader = True
09  GridView1.GridLines = GridLines.Both
10  GridView1.PagerSettings.Visible = False
11  GridView1.DataBind()
12 End If
13 
14 ChangeControlsToValue(GridView1)
15 Response.ClearContent()
16 
17 Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls")
18 
19 Response.ContentType = "application/excel"
20 
21 Dim sWriter As New StringWriter()
22 
23 Dim hTextWriter As New HtmlTextWriter(sWriter)
24 
25 Dim hForm As New HtmlForm()
26 
27 GridView1.Parent.Controls.Add(hForm)
28 
29 hForm.Attributes("runat") = "server"
30 
31 hForm.Controls.Add(GridView1)
32 
33 hForm.RenderControl(hTextWriter)
34 
35 Response.Write(sWriter.ToString())
36 
37 Response.[End]()
38End Sub
39 
40Private Sub ChangeControlsToValue(gridView As Control)
41 Dim literal As New Literal()
42 
43 For i As Integer = 0 To gridView.Controls.Count - 1
44  If gridView.Controls(i).[GetType]() = GetType(LinkButton) Then
45 
46   literal.Text = TryCast(gridView.Controls(i), LinkButton).Text
47   gridView.Controls.Remove(gridView.Controls(i))
48   gridView.Controls.AddAt(i, literal)
49  ElseIf gridView.Controls(i).[GetType]() = GetType(DropDownList) Then
50   literal.Text = TryCast(gridView.Controls(i), DropDownList).SelectedItem.Text
51 
52   gridView.Controls.Remove(gridView.Controls(i))
53 
54 
55   gridView.Controls.AddAt(i, literal)
56  ElseIf gridView.Controls(i).[GetType]() = GetType(CheckBox) Then
57   literal.Text = If(TryCast(gridView.Controls(i), CheckBox).Checked, "True", "False")
58   gridView.Controls.Remove(gridView.Controls(i))
59   gridView.Controls.AddAt(i, literal)
60  End If
61  If gridView.Controls(i).HasControls() Then
62 
63 
64   ChangeControlsToValue(gridView.Controls(i))
65 
66  End If
67 Next
68 
69End Sub
This is how excel sheet will look like. Hope this helps.
Number only textbox using javascript or regularexpressionvalidator

Numeric or Number Only TextBox Using JavaScript or RegularExpressionValidator.

In this example i am going to decsribe how create Numeric or Number only textbox using javascript or regular expression Validator which accept only numbers in asp.net web page.



1. Number only textbox using javascript.

Go to html source of aspx page and write below mentioned script in head section of page.


Call this function in onKeyPress event of textbox.
Write this code in html source of textbox.

<asp:TextBox ID="TextBox2" runat="server" 
             onKeyPress="return numberOnlyExample();">
</asp:TextBox>


We can also do this programmetically in code behind like this.

on Page_Load event of page add onKeyPress attribute to textbox and call the function to accept only numerics.

protected void Page_Load(object sender, EventArgs e)
    {
       TextBox2.Attributes.Add("onkeypress", "return ((window.event.keyCode >= 48 && window.event.keyCode <= 58))");
    }

2. Creating Numeric or Number only textbox using Regular Expression Validator. Drag and place RegularExpressionValidator control on aspx page and set it's properties as mentioned below in html code. Set ControlToValidate property to textbox1. Set ValidationExpression. Set ErrorMessage.
HTML Source
<asp:RegularExpressionValidator 
     ID="RegularExpressionValidator1" 
     runat="server" 
     ControlToValidate="TextBox1"
     ErrorMessage="Please Enter only Numbers" 
     ValidationExpression="\d+">
</asp:RegularExpressionValidator>
Hope this helps
Delete Duplicate Records In Sql
Remove or Delete duplicate records or rows from ms sql server database table.

In this post i am going to describe different methods of deleting duplicate records or rows from sql server database table.

I am using Employees table with FirstName and Department columns.







Remove Duplicate Records In Sql
First Method.

Delete duplicate records/rows by creating identity column.


duplicate records in table looks like shown in first image.

First of all we need to create a identity column in our table by using code mentioned below.

And table will look like image on the left.



1ALTER TABLE dbo.Employees ADD ID INT IDENTITY(1,1)

Now write this query to delete duplicate rows.

1DELETE FROM dbo.Employees
2WHERE ID NOT IN (SELECT MIN(ID)
3FROM dbo.Employees GROUP BY FirstName,Department)

This should remove all duplicate records from table.


Second Method.

Delete duplicate records using Row_Number()


If you do not want to make any changes in table design or don't want to create identity column on table then you can remove duplicate records using Row_Number in sql server 2005 onwards.

for this write below mentioned code and execute.

1WITH DuplicateRecords AS
2(
3SELECT *,row_number() OVER(PARTITION BY FirstName,Department ORDER BY
4 
5FirstName)
6AS RowNumber FROM dbo.Employees
7)
8DELETE FROM DuplicateRecords WHERE RowNumber>1

This should remove all duplicate records from table.


Third Method.

Remove duplicate rows/Records using temporary table


Use below mentioned code to delete duplicates by moving them to temporary table using DISTINCT.

1SELECT DISTINCT * INTO TempTable FROM dbo.Employees
2GROUP BY FirstName,Department
3HAVING COUNT(FirstName) > 1
4 
5DELETE dbo.Employees WHERE FirstName
6IN (SELECT FirstName FROM TempTable)
7 
8INSERT dbo.Employees SELECT * FROM TempTable
9DROP TABLE TempTable


Remove delete Duplicate Rows In Sql
And result will be as shown.

Have fun.