Friday, 2 December 2011

Asp.Net QueryString Example

In this post i am explaining how to use querystrings.

Example url with querystring can be something similar like this

http://yahoo.com/defauld.aspx?variable1=value1&variable2=value2

Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo


1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?Value=" +
4txtData.Text);
5}

Pass Crystal Report Parameters Programmatically


Pass crystal report parameters programmatically in Asp.Net 2.0,3.5.

In this post i am explaining how to pass parameters to crystal reports programmatically in code behind of asp.net web page.

For this i am using northwind database and products table.

I have put one text box on the page and report will display details of product based on product id entered by user.




To know how to create crystal report in Asp.Net .

If u want to know how to create crystal reports with parameters in winforms or windows application then read this.

Open crystal report in design view, right click on it and select Field Explorer

Now select Parameter Fields and select new to add new parameter to report.

Name it as ProductID and remember it.

Now click on Special Fields in Field Explorer and select Record Selection Formula.

Select is equal to and {?ProductID} from the dropdowns and click on OK.

Click on smart tag of reportviewer control and uncheck Database logon prompting and parameter prompting as we will provide these info in code behind.


HTML markup of aspx page

<form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                Enter Product ID :
            </td>
            <td>
                <asp:TextBox ID="txtProductID" runat="server">
                </asp:TextBox>
                </td>
            <td>
                <asp:Button ID="btnReport" runat="server" 
                            Text="Show Report" 
                            onclick="btnReport_Click" 
                            Width="108px" />
                </td>
        </tr>
    </table>
    <br />
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
        AutoDataBind="True" EnableDatabaseLogonPrompt="False" 
        EnableParameterPrompt="False" Height="1039px" 
        ReportSourceID="CrystalReportSource1" 
        ReuseParameterValuesOnRefresh="True" 
        Width="901px" DisplayGroupTree="False" />
    <CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
        <Report FileName="CrystalReport.rpt">
        </Report>
    </CR:CrystalReportSource>
    </form>


Now go to code behind of the page and add below mentioned namespace for crystal reports.

1using CrystalDecisions.Shared;
2using CrystalDecisions.CrystalReports.Engine;

Write this code in Page_Load event of the page

1protected void Page_Load(object sender, EventArgs e)
2    {
3        if (Page.IsPostBack) CrystalReportViewer1.Visible = true;
4        else
5            CrystalReportViewer1.Visible = false;
6    }

Generate click event for button to shaow report and write this code.

01protected void btnReport_Click(object sender, EventArgs e)
02    {   //Create report document
03        ReportDocument crystalReport = new ReportDocument();
04 
05        //Load crystal report made in design view
06        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
07 
08        //Set DataBase Login Info
09        crystalReport.SetDatabaseLogon
10            ("amitjain", "password", @"AMITJAIN\SQL", "Northwind");
11 
12        //Provide parameter values
13        crystalReport.SetParameterValue("ProductID", txtProductID.Text);
14        CrystalReportViewer1.ReportSource = crystalReport;
15    }

Build the solution and run.

Hide Show Div Using JQuery Asp.Net

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.



Export GridView To Excel ASP.NET

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 .







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    }
This is how excel sheet will look like. Hope this helps.

jQuery Fixed Header Scrollable GridView

Jquery fixed header scrollable gridview in asp.net
Fixed Header Scrollable Gridview Using jQuery in ASP.NET.

In this example im going to describe how to create fixed header scrollable gridview using jquery.

I have used northwind database to populate gridview and jquery fixed header plugin.




Thursday, 1 December 2011

Searching in HTML table with javascript

I have search a lot of article for how to make search in HTML table but i didn't find any good article so i wrote my own article for that,
Here is a script given bellow for how to make search in HTML table the question is that how to use this code so here is the step by step instructions :-
  • Copy and paste JavaScript code inside <head> tag.
  • Add Text box at the header row ( first row ) of your table in which you want to add functionality search.
  • Call the function searchRows at the onkeyup event of the text box.

How to Get Server Name and Server Port No in Asp.Net from Request Object




string link = "http://" + Request.ServerVariables["server_name"].ToString();
                if (Request.ServerVariables["SERVER_PORT"].ToString() !=null &&
Request.ServerVariables["SERVER_PORT"].ToString() != "")