Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for July, 2009

Asp .net Web.config Configuration File

Posted by Viral Sarvaiya on July 30, 2009

What is Web.Config File?

Web.config file, as it sounds like is a configuration file for the Asp .net web application. An Asp .net application has one web.config file which keeps the configurations required for the corresponding application. Web.config file is written in XML with specific tags having specific meanings.
What is Machine.config File?

As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
What can be stored in Web.config file?

There are number of important settings that can be stored in the configuration file. Here are some of the most frequently used configurations, stored conveniently inside Web.config file..

1. Database connections
2. Session States
3. Error Handling
4. Security

Database Connections:

The most important configuration data that can be stored inside the web.config file is the database connection string. Storing the connection string in the web.config file makes sense, since any modifications to the database configurations can be maintained at a single location. As otherwise we’ll have to keep it either as a class level variable in all the associated source files or probably keep it in another class as a public static variable.

But it this is stored in the Web.config file, it can be read and used anywhere in the program. This will certainly save us a lot of alteration in different files where we used the old connection.

Lets see a small example of the connection string which is stored in the web.config file.



<add key="ConnectionString"

value="server=localhost;uid=sa;pwd=;database=DBPerson" />



As you can see it is really simple to store the connection string in the web.config file. The connection string is referenced by a key which in this case is “ConnectionString”. The value attribute of the configuration file denotes the information about the database. Here we can see that if has database name, userid and password. You can define more options if you want.

There is a very good website that deals with all sorts of connection strings. Its called , in the website you will find the connection strings for most of the databases.

Lets see how we access the connection string from our Asp .net web application.

using System.Configuration;

string connectionString = (string )ConfigurationSettings.AppSettings["ConnectionString"];

The small code snippet above is all that is needed to access the value stored inside the Web.config file.
Session States:

Session in Asp .net web application is very important. As we know that HTTP is a stateless protocol and we needs session to keep the state alive. Asp .net stores the sessions in different ways. By default the session is stored in the asp .net process. You can always configure the application so that the session will be stored in one of the following ways.

1) Session State Service

There are two main advantages of using the State Service. First the state service is not running in the same process as the asp .net application. So even if the asp .net application crashes the sessions will not be destroyed. Any advantage is sharing the state information across a Web garden (Multiple processors for the same computer).

Lets see a small example of the Session State Service.

<sessionState mode="StateServer" stateConnectionString="tcpip=" sqlConnectionString="data source=;user id=sa;password='' cookieless="false" timeout="20"/>

The attributes are self explanatory but I will go over them.

mode: This can be StateServer or SqlServer. Since we are using StateServer we set the mode to StateServer.

stateConnectionString: connectionString that is used to locate the State Service.

sqlConnectionString: The connection String of the sql server database.

cookieless: Cookieless equal to false means that we will be using cookies to store the session on the client side.

2) SQL Server

The final choice to save the session information is using the Sql Server 2000 database. To use Sql Server for storing session state you need to do the following:

1) Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store the session.

You web.config settings will look something like this:

<sessionState mode = "SqlServer" stateConnectionString="tcpip=" sqlConnectionString="data source="SERVERNAME;user id=sa;password='' cookiesless="false" timeout="20"/>

SQL Server lets you share session state among the processors in a Web garden or the servers in a Web farm. Apart from that you also get additional space to store the session. And after that you can take various actions on the session stored.

The downside is SQL Server is slow as compared to storing session in the state in process. And also SQL Server cost too much for a small company.
3) InProc:

This is another Session State. This one is mostly used for development purposes. The biggest advantage of using this approach is the applications will run faster when compared to other Session state types. But the disadvantage is Sessions are not stored when there is any problem that occurs with the application, when there is a small change in the files etc., Also there could be frequent loss of session data experienced..
Error Handling:

Error handling is one of the most important part of any web application. Each error has to be caught and suitable action has to be taken to resolve that problem. web.config file lets us configure, what to do when an error occurs in our application.

Check the following xml tag in the web.config file that deals with errors:

<customErrors mode = "On">

<error statusCode = "404" redirect = "errorPage.aspx" />


This tells the to display custom errors from a remote client or a local client and to display a page named errorPage.aspx. Error “404” is “Page not found” error.

If custom error mode is turned “off” than you will see default error message. This error messages are good for debugging purposes but should never be exposed to the users. The users should always be presented with friendly errors if any.

The most critical aspect of any application is the security. offers many different types of security method which can be used depending upon the condition and type of security you need.

1) No Authentication:

No Authentication means “No Authentication” 🙂 , meaning that will not implement any type of security.

2) Windows Authentication:

The Windows authentication allows us to use the windows user accounts. This provider uses IIS to perform the actual authentication, and then passes the authenticated identity to your code. If you like to see that what windows user is using the application you can use:


This returns the DOMAIN\UserName of the current user of the local machine.

3) Passport Authentication:

Passport Authentication provider uses Microsoft’s Passport service to authenticate users. You need to purchase this service in order to use it.

4) Forms Authentication:

Forms Authentication uses HTML forms to collect the user information and than it takes required actions on those HTML collected values.

In order to use Forms Authentication you must set the Anonymous Access checkbox checked. Now we need that whenever user tries to run the application he/she will be redirected to the login page.

<authentication mode="Forms">

<forms loginUrl = "frmLogin.aspx" name="3345C" timeout="1"/>



<deny users="?" />


As you can see we set the Authentication mode to “Forms”. The forms loginUrl is the first page being displayed when the application is run by any user.

The authorization tags has the deny users element which contains “?”, this means that full access will be given to the authenticated users and none access will be given to the unauthenticated users. You can replace “?” with “*” meaning that all access is given to all the users no matter what.

Posted in ASP.NET | Tagged: , , , , , , , , , , | Leave a Comment »

Disable copy & paste in textboxes

Posted by Viral Sarvaiya on July 28, 2009

Below is the line of code to disable copy & paste event in textbox.

for textbox

<asp:TextBox onCopy=”return false” onPaste=”return false” ID=”textboxname” runat=”server” ></asp:TextBox>

For HTML textbox tag

<input name="textboxname" type="text" id="textboxname" onCopy="return false" onPaste="return false" />

Posted in ASP.NET | Tagged: , , , , | Leave a Comment »

Count Online Visitor in ASP.Net & VB.Net

Posted by Viral Sarvaiya on July 28, 2009

Place the following code in Global.asax file. Here, we track the active Sessions for our web application. There are three subroutines into which we will be looking to do this – Application_OnStart, Session_OnStart, Session_OnEnd.

Step-1 :

In the Application_OnStart subroutine, we have to set the user count to 0, when the server starts the application.

Sub Application_OnStart (Sender as Object, E as EventArgs)
     ' Set user count to 0 when start the application
     Application("ActiveUsers") = 0
 End Sub

Step-2 :

In the Session_OnStart subroutine, we have to increament the Activeuser by 1:

Sub Session_OnStart (Sender as Object, E as EventArgs)
      Application("ActiveUsers") = Cint(Application("ActiveUsers")) + 1
End Sub

In this case you have to set Timeout – you don’t need to put anything here, but the default Timeout is 20 minutes, so you can change it depending on the needs of your particular application.

To set the session start time, we add (Session(”Start”) = Now). Basically, when the user hits the site and opens a web page ( page), at the time of opening the page, the session starts. Next, we increase the active visitors count when we start the session (Application(”ActiveUsers”) = Cint(Application(”ActiveUsers”)) + 1 ). The Application lock & unlock adds more stability to the counting.

Step-3 :

we must decrement the number of Active Users on the basis of online sessions in the Session_OnEnd subroutine:

Sub Session_OnEnd(Sender as Object, E as EventArgs)
Application("ActiveUsers") = Cint(Application("ActiveUsers")) - 1
End Sub

Step-4 :

Then you can place the following code to access the Application(”ActiveUsers”) in .aspx file

Dim intNumber as Integer
intNumber =Application("ActiveUsers")
response.write (intNumber )
%> Currently Online

Posted in ASP.NET | Tagged: , | 3 Comments »

Introduction to Windows Presentation Foundation

Posted by Viral Sarvaiya on July 27, 2009


The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

The following illustration gives you an overview of the main new features of WPF

Separation of Appearance and Behavior

WPF separates the appearance of an user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by databinding, events and commands. The separation of appearance and behavior brings the following benefits:

  • Appearance and behaviour are loosely coupled
  • Designers and developers can work on separate models.
  • Graphical design tools can work on simple XML documents instead of parsing code.

Rich composition

Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combobox to choose a video file.

    <StackPanel Orientation="Horizontal">
        <Image Source="speaker.png" Stretch="Uniform"/>
        <TextBlock Text="Play Sound" />

Highly customizable

Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.

The following example shows an default WPF button and a customized button.

Resolution independence

All measures in WPF are logical units – not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface stays the same size – if just gets crispier. Since WPF builds on a vector based rendering engine its incredibly easy to build scaleable user interfaces.

How to create a simple WPF application

In Visual Studio 2008

Open Visual Studio 2008 and choose “File”, “New”, “Project…” in the main menu. Choose “WPF Application” as project type.

Choose a folder for your project and give it a name. Then press “OK”

Visual Studio creates the project and automatically adds some files to the solution. A Window1.xaml and an App.xaml. The structure looks quite similar to WinForms, except that the Window1.designer.cs file is no longer code but it’s now declared in XAML as Window1.xaml

Open the Window1.xaml file in the WPF designer and drag a Button and a TextBox from the toolbox to the Window

Select the Button and switch to the event view in the properties window (click on the little yellow lightning icon). Doubleclick on the “Click” event to create a method in the codebehind that is called, when the user clicks on the button.

Note: If you do not find a yellow lightning icon, you need to install the Service Pack 1 for VisualStudio on your machine. Alternatively you can doubleclick on the button in the designer to achieve the same result.

Visual Studio automatically creates a method in the code-behind file that gets called when the button is clicked.

private void button1_Click(object sender, RoutedEventArgs e)
    textBox1.Text = "Hello WPF!";

The textbox has automatically become assigned the name textBox1 by the WPF designer. Set text Text to “Hello WPF!” when the button gets clicked and we are done!. Start the application by hit [F5] on your keyboard.

Isn’t this cool!

Learn PWF click here

Posted in ASP.NET | Tagged: , | Leave a Comment »

Gridview – insert, update, delete

Posted by Viral Sarvaiya on July 27, 2009


Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.

Step 1. Create Class File ‘CustomersCls.cs’

We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section.

Let us write five methods in the class file as follows

public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
// Write your own Insert statement blocks
public DataTable Fetch()
// Write your own Fetch statement blocks, this method should return a DataTable
public DataTable FetchCustomerType()
// Write your own Fetch statement blocks to fetch Customer Type from its master table and this method

//should return a DataTable
public void Update(int CustomerCode, string CustomerName, string Gender, string City, string State,string CustomerType)
// Write your own Update statement blocks.
public void Delete(int CustomerCode)

// Write your own Delete statement blocks.

Step 2: Make Design File ‘Default.aspx’

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be
converted to TemplateField columns except the Delete column.

Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] – Gender

Now again select Edit Template, choose column[1] – Gender, replace the TextBox with a DropDownList,name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval(”Gender”) to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] – State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.

Column[4] – Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] – Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.

Source Code of the GridView Control

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataKeyNames=”Code, Type”

OnRowCancelingEdit=”GridView1_RowCancelingEdit” OnRowDataBound=”GridView1_RowDataBound”

OnRowEditing=”GridView1_RowEditing” OnRowUpdating=”GridView1_RowUpdating”

OnRowCommand=”GridView1_RowCommand” ShowFooter=”True” OnRowDeleting=”GridView1_RowDeleting”>

<asp:TemplateField HeaderText=”Name” SortExpression=”Name”> <EditItemTemplate>
<asp:TextBox ID=”txtName” runat=”server” Text=’<%# Eval(”Name”) %>’></asp:TextBox>
<asp:TextBox ID=”txtNewName” runat=”server”></asp:TextBox> </FooterTemplate>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Bind(”Name”) %>’></asp:Label>

<asp:TemplateField HeaderText=”Gender”>
<asp:DropDownList ID=”cmbGender” runat=”server” SelectedValue=’<%# Eval(”Gender”) %>’>
<asp:ListItem Value=”Male” Text=”Male”></asp:ListItem>
<asp:ListItem Value=”Female” Text=”Female”></asp:ListItem>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(”Gender”) %>’></asp:Label>
<asp:DropDownList ID=”cmbNewGender” runat=”server” >
<asp:ListItem Selected=”True” Text=”Male” Value=”Male”></asp:ListItem>
<asp:ListItem Text=”Female” Value=”Female”></asp:ListItem> </asp:DropDownList>

<asp:TemplateField HeaderText=”City”>
<asp:TextBox ID=”txtCity” runat=”server” Text=’<%# Bind(”City”) %>’></asp:TextBox>
<asp:TextBox ID=”txtNewCity” runat=”server” ></asp:TextBox>
<asp:Label ID=”Label3″ runat=”server” Text=’<%# Bind(”City”) %>’></asp:Label>

<asp:TemplateField HeaderText=”State” SortExpression=”State”>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(”State”) %>’></asp:Label>
<asp:TextBox ID=”txtNewState” runat=”server” ></asp:TextBox>
<asp:Label ID=”Label4″ runat=”server” Text=’<%# Bind(”State”) %>’></asp:Label>

<asp:TemplateField HeaderText=”Type”>
<asp:DropDownList ID=”cmbType” runat=”server” DataTextField=”Type” DataValueField=”Type”>

<asp:Label ID=”Label5″ runat=”server” Text=’<%# Eval(”Type”) %>’></asp:Label>
<asp:DropDownList ID=”cmbNewType” runat=”server” DataTextField=”Type” DataValueField=”Type”>


<asp:TemplateField HeaderText=”Edit” ShowHeader=”False”>
<asp:LinkButton ID=”LinkButton1″ runat=”server” CausesValidation=”True” CommandName=”Update”

<asp:LinkButton ID=”LinkButton2″ runat=”server” CausesValidation=”False” CommandName=”Cancel”

<asp:LinkButton ID=”LinkButton2″ runat=”server” CausesValidation=”False” CommandName=”AddNew”

Text=”Add New”></asp:LinkButton>
<asp:LinkButton ID=”LinkButton1″ runat=”server” CausesValidation=”False” CommandName=”Edit”
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” ShowHeader=”True” />

Step 3: Make Code-behind File ‘Default.aspx.cs’

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows

CustomersCls customer=new CustomersCls();

Then create a private method ‘FillCustomerInGrid’ to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header,data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.

private void FillCustomerInGrid()
DataTable dtCustomer= customer.Fetch();

if (dtCustomer.Rows.Count>0)
GridView1.DataSource = dtCustomer;
GridView1.DataSource = dtCustomer;

int TotalColumns = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
GridView1.Rows[0].Cells[0].Text = “No Record Found”;

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not.Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as “No Record Found”, this text will be displayed if the GridView is empty without any rows and you can see
both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,

protected void Page_Load(object sender, EventArgs e)
If (!IsPostBack)

Fill DropDownList in GridView with dynamic values

In column[4] – Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
DropDownList cmbType = (DropDownList)e.Row.FindControl(”cmbType”);

if (cmbType != null)
cmbType.DataSource = customer.FetchCustomerType();
cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

if (e.Row.RowType == DataControlRowType.Footer)
DropDownList cmbNewType = (DropDownList)e.Row.FindControl(”cmbNewType”);
cmbNewType.DataSource = customer.FetchCustomerType();

Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows

cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
if (e.CommandName.Equals(”AddNew”))
TextBox txtNewName=(TextBox)GridView1.FooterRow.FindControl(”txtNewName”);
DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl(”cmbNewGender”);
TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl(”txtNewCity”);
TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl(”txtNewState”);
DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl(”cmbNewType”);

customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text,
cmbNewType.SelectedValue) ;

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database
and listed in the GridView control.

Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
GridView1.EditIndex = e.NewEditIndex;

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
GridView1.EditIndex = -1;

You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl(”txtName”);
DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl(”cmbGender”);
TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl(”txtCity”);
DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl(”cmbType”);


GridView1.EditIndex = -1;

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method.

The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Delete in GridView

To delete a row from the customer table, add the following lines of code in the GridView’s RowDeleting event. Here you have to pass the unique Code of customer which is in GridView1.DataKeys[e.RowIndex].Values[0].ToString() to the Delete method of the CustomersCls class.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

Posted in ASP.NET | Tagged: , , , , , | 2 Comments »

about the LINQ.

Posted by Viral Sarvaiya on July 24, 2009


This article provides an introduction to employing LINQ to SQL within a Windows Forms application. The article will address the incorporation of LINQ to SQL into a WinForms project, how to use LINQ to SQL to select, insert, update, and delete data, and how to use LINQ to SQL to execute stored procedures. Select query examples will demonstrate ordering, filtering, aggregation, returning typed lists, returning single objects and values, and how to query across entity sets (which are essentially related tables associated by foreign keys).

For more detail click here.

Posted in ASP.NET, Sql Server | Tagged: , , | Leave a Comment »

New ASP.NET Charting Control:

Posted by Viral Sarvaiya on July 23, 2009

Microsoft recently released a cool new ASP.NET server control – <asp:chart /> – that can be used for free with ASP.NET 3.5 to enable rich browser-based charting scenarios:

Once installed the <asp:chart/> control shows up under the “Data” tab on the Toolbox, and can be easily declared on any ASP.NET page as a standard server control:

<asp:chart /> supports a rich assortment of chart options – including pie, area, range, point, circular, accumulation, data distribution, ajax interactive, doughnut, and more.  You can statically declare chart data within the control declaration, or alternatively use data-binding to populate it dynamically.  At runtime the server control generates an image (for example a .PNG file) that is referenced from the client HTML of the page using a <img/> element output by the <asp:chart/> control.  The server control supports the ability to cache the chart image, as well as save it on disk for persistent scenarios.  It does not require any other server software to be installed, and will work with any standard ASP.NET page.

To get a sense of how to use the <asp:chart /> control I recommend downloading the Microsoft Chart Controls Sample Project.  This includes over 200 ASP.NET sample pages that you can run locally.  Just open the web project in VS 2008 and hit run to see them in action – you can then open the .aspx source of each to see how they are implemented.

The below example (under Chart Types->Line Charts->3D Line and Curve Charts) demonstrates how to perform Line, Spline and StepLine charting:

The below example (under Chart Types->Pie and Doughnut Charts) demonstrates a variety of pie and 3D doughnut options:

The below example (under Chart Types->Advanced Financial Charts) demonstrates some graph charts:

In addition to the above samples, you can download the Microsoft Chart Control Documentation or ask questions on the Chart Controls Forum to learn more.

This should provide a useful (and free) addition to your standard ASP.NET toolkit of functionality, and enable you to easily add richer visualization and data workflow scenarios to your ASP.NET applications.

Hope this helps,

Posted in ASP.NET | Tagged: , , | Leave a Comment »

ASP.NET MVC Framework

Posted by Viral Sarvaiya on July 23, 2009

One of the things that many people have asked for over the years with ASP.NET is built-in support for developing web applications using a model-view-controller (MVC) based architecture.

Last weekend at the Alt.NET conference in Austin I gave the first public demonstration of a new ASP.NET MVC framework that my team has been working on.  You can watch a video of my presentation about it on Scott Hanselman’s blog here.

We’ll be releasing a public preview of this ASP.NET MVC Framework a little later this year.  We’ll then ship it as a fully supported ASP.NET feature in the first half of next year.

What is a Model View Controller (MVC) Framework?

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

  • “Models” in a MVC based application are the components of the application that are responsible for maintaining state.  Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
  • “Views” in a MVC based application are the components responsible for displaying the application’s user interface.  Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
  • “Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI.  In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application.  Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

The MVC pattern can also help enable red/green test driven development (TDD) – where you implement automated unit tests, which define and verify the requirements of new code, first before you actually write the code itself.

A few quick details about the ASP.NET MVC Framework

I’ll be doing some in-depth tutorial posts about the new ASP.NET MVC framework in a few weeks once the bits are available for download (in the meantime the best way to learn more is to watch the video of my presentation).

A few quick details to share in the meantime about the ASP.NET MVC framework:

  • It enables clean separation of concerns, testability, and TDD by default.  All core contracts within the MVC framework are interface based and easily mockable (it includes interface based IHttpRequest/IHttpResponse intrinsics).  You can unit test the application without having to run the Controllers within an ASP.NET process (making unit testing fast).  You can use any unit testing framework you want to-do this testing (including NUnit, MBUnit, MS Test, etc).
  • It is highly extensible and pluggable.  Everything in the MVC framework is designed so that it can be easily replaced/customized (for example: you can optionally plug-in your own view engine, routing policy, parameter serialization, etc).  It also supports using existing dependency injection and IOC container models (Windsor, Spring.Net, NHibernate, etc).
  • It includes a very powerful URL mapping component that enables you to build applications with clean URLs.  URLs do not need to have extensions within them, and are designed to easily support SEO and REST-friendly naming patterns.  For example, I could easily map the /products/edit/4 URL to the “Edit” action of the ProductsController class in my project above, or map the /Blogs/scottgu/10-10-2007/SomeTopic/ URL to a “DisplayPost” action of a BlogEngineController class.
  • The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and .Master markup files as “view templates” (meaning you can easily use existing ASP.NET features like nested master pages, <%= %> snippets, declarative server controls, templates, data-binding, localization, etc).  It does not, however, use the existing post-back model for interactions back to the server.  Instead, you’ll route all end-user interactions to a Controller class instead – which helps ensure clean separation of concerns and testability (it also means no viewstate or page lifecycle with MVC based views).
  • The ASP.NET MVC framework fully supports existing ASP.NET features like forms/windows authentication, URL authorization, membership/roles, output and data caching, session/profile state management, health monitoring, configuration system, the provider architecture, etc.


If you are looking to build your web applications using a MVC approach, I think you’ll find this new ASP.NET MVC Framework option very clean and easy to use.  It will enable you to easily maintain separation of concerns in your applications, as well as facilitate clean testing and TDD.

I’ll post more tutorials in the weeks ahead on how the new MVC features work, as well as how you can take advantage of them.

i took this from:

Posted in ASP.NET | Tagged: , , | Leave a Comment »

Export Excel file from sql server

Posted by Viral Sarvaiya on July 23, 2009

Sql Server is provide the facility to export your data to the Excel file. for more read please click here

Posted in Sql Server | Tagged: , , | Leave a Comment »

Get HTML Input Controls Values Server Side

Posted by Viral Sarvaiya on July 17, 2009

Many times a need arises to use HTML Controls rather than HTML controls. In that case the issue is how to get the values Server Side. See the example below

<input type = “text” id = “txt” value = “Hello” name = “txt” />

Now the name attribute is important Since Server Side You will need to access the controls using the name field. It is not necessary that the ID is same as the name it can be different

On Server Side

If Not Request.Params(“txt”) Is Nothing Then

Dim strVal As String = Request.Params(“txt”)

End If

Now most interesting part, suppose you have multiple TextBoxes and you need to get values of all of them then just give all of them same name attribute different ID is not an issue

<input type = “text” id = “txt1″ value = “Hello” name = “txt” />

<input type = “text” id = “txt2″ value = “Hello” name = “txt” />

<input type = “text” id = “txt3″ value = “Hello” name = “txt” />

<input type = “text” id = “txt4″ value = “Hello” name = “txt” />

<input type = “text” id = “txt5″ value = “Hello” name = “txt” />

Then on server Side

If Not Request.Params(“txt”) Is Nothing

Then Dim arr() As String = Request.Params(“txt”).Split(“,”)

For i As Integer = 0 To  arr.Length – 1

Dim strVal As String= arr(i)

Next End If

You will get values of all TextBoxes separated by comma.

Now you can split them and get it into an array as shown above

and the other way is also there, you can also use the “Request.form(“txt”) for geting the value of the html control.

This technique works for
1. TextBoxes
2. CheckBoxes
3. RadioButton
4.Select (DropDownList)

Posted in ASP.NET | Tagged: , | Leave a Comment »

%d bloggers like this: