Friday 30 December 2011

How can we fetch dropdown selected value in textbox using C#

Hi if anyone want to display dropdown selected data in textbox than firstly set the Autopostback=true for Dropdown and write the code given below:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show ddltext</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddldetails" runat="server" AutoPostBack="true" 
        onselectedindexchanged="ddldetails_SelectedIndexChanged">
<asp:ListItem Value="0">--Select--</asp:ListItem>
<asp:ListItem Value="1">Delhi</asp:ListItem>
<asp:ListItem Value="2">Calcutta</asp:ListItem>
<asp:ListItem Value="3">Pune</asp:ListItem>
</asp:DropDownList>

Sunday 25 December 2011

SEO TIPS:-


Key factors of SEO that will make site more searchable and popular are :-

Domain Name - Short names are easiest way  to remember ! Include short Primary Keywords ! without hyphens were possible. 

Domain Extension - .com or .net for the Global Market.


URL Names - include relevant keywords - unique to each page.

Robots.txt - A file which permits or denies access to robots or crawlers to areas of your site.

Navigation Structure - Keep it simple. 


 H1 Tags - Use for the short on page content description. 


H2 and H3 Tags- Use for Headings for sub category's within the Content

Page Content - Critical Component

Thursday 8 December 2011

Mobile number validation using javascript

function CheckIndianNumber(IndianNumber) {

    var IndNum = /^\d{10}$/;

    if (IndNum.test(IndianNumber)) {

//        alert("Your Mobile Number Is Valid.");

    }

Validation in textbox only accept number using javascrit


function validate(key)
{
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('txtPhn');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57))
{
return false;
}

Wednesday 7 December 2011

accept only alpabets in textbox using javascript

write the code on jscript page:-



function ValidateAlpha()
{
var keyCode = window.event.keyCode;
if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)
{
window.event.returnValue = false;
alert("Enter only letters");
}
}

Friday 2 December 2011

How To Add Blogger's Read More Functions To Customized templates

To add the code for Jump Links functionality to your Blogger template...

Go to Layout>Edit HTML in your Blogger dashboard and ensure you have checked the "Expand widget templates" box.

Then using your browser's search function, locate the following line of code:
<data:post.body/>
Depending on your individual template, you may find this enclosed between <p&gt or <div> tags. We need to leave these tags intact.

If you've added any other "Read more" hacks to your template (or have added other conditional statements to the Blog Posts section), you may discover more than one instance of <data:post.body/>. If this is the case, you need to edit the section which has <b:if cond='data.blog.url != data:blog.homepageUrl> a line or two above this.

Export Selected GridView Rows To Excel

Export Selected GridView Rows to excel
Export Selected GridView Rows To Excel in asp.net 2.0,3.5,4.0 using C# and VB.NET.

In this post i am going to explain how to export selected gridview rows to ms excel in asp.net.

I have used northwind database and customers table to populate gridview.



read how to install northwind database for northwind database installation in sql server 2008.





In this post i am listing some GridView EditItemTemplate examples in Asp.Net 2.0,3.5 with Csharp and VB.NET.





Ajax autocomplete extender textbox in GridView

Example of Ajax Autocomplete Extender TextBox in EditItemTemplate of GridView.





Install Configure Windows Server AppFabric




Install Windows Server Appfabric
Install,Configure Windows Server AppFabric cache services in asp.net 3.5 and 4.0.

Here i am explaining steps to install and configure windows server appfabric cache services in asp.net 3.5 and 4.0.

1. Download and run windows server appfabric from this link

Select the features you want to install, Confirm the next screen and finish the installation.



Install AppFabric

After installation is finished, Go start > all programs> windows server AppFabric and launch configure AppFabric

Sql Query Optimization

Sql Query Optimization in MS SQL Server To Improve Performance of ASP.NET web applications.

Data retrieval FROM database in asp.net applications is a most common task and writing optimized queries can have a huge impact on perfirmance of application if database is huge or containing thousands of records in table.

Here i am mentioning few tips to remeber while writing sql queries for optimal performance.
1. Use columns name instead of * in SELECT statements.

1Use:
2 
3SELECT column1,column2,column3 FROM TableName
4 
5Insted of
6 
7SELECT * FROM TableName

Create Setup And Deployment Project in Visual Studio 2008/2010


Create setup Project In Visual Studio

In this example i am going to explain how to create setup and deployment project for winforms windows application using visual studio 2005/2008/2010.

Similar approach can be applied for creating setup project for web application as well.











First of all create any sample windows/web application.

Create setup project

right click on solution explorer root and select Add > New project 


In add new project dialog box select setup and deployment from other project types and then select Setup Project.


In the setup project file system editor window, right click on Application folder > Add > Project Output 


Now select primary output from next dialog box and click on OK.



Right click on User's desktop and create shortcut to primary output in application folder.


Similarly add shortcut in user's program menu.


Build the project by right clicking on setup project name and run the setup.


Hope this helps 




Download the sample code attached 

Maintain Scroll Position On After Postback in Asp.Net

Maintain scroll position after postback
Maintain Scroll Position on or After Postback in Asp.Net 2.0 3.5.

In this example i'm explaining different methods of maintaining scroll position on/after postback in asp.net 2.0,3.5 web pages or applications.









Forms Authentication In Asp.Net

Forms Authentication in asp.net


In examples below i'm explaining how to use forms authentication in Asp.Net and forms authentication tickets in Asp.net.












Forms Authentication In Asp.Net 2.0 and 3.5


Forms Authentication in ASP.NET is technique to decide how users can access your web application.

Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles.

we can manage the access through web.config file or folder level access and through multiple web.config files using forms authentication.




Forms Authentication Ticket In Asp.Net 2.0 And 3.5


In this article i am going to describe how to implement Forms authentication tickets and manage user roles based access in ASP.NET using C# and multiple web.config files



Bypass Forms Authentication Or Skip Authorization


Some readers ask me how to skip or bypass forms authentication or Authorization for selected pages in asp.net or a scenario where only few pages on site needs user to log in rest can be accessed without login.

Select Find Nth Highest Salary Record In Sql Server

Find or Select nth highest salary record in ms sql

This is most frequentky asked question how to select or get nth highest record or nth row/record from any column of sql table.

for example select get or fetch 2nd (second highest) or nth highest salary of employee or 10th highest record from the table.

There are various ways to achieve this result, i've mentioned few here.









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.