Add TextBox value to DropDownList or Html SELECT using jQuery

You have a dropdownlist or an HTML Select with you. You now want to add additional options to the SELECT which you enter in the textbox, on the click of a button.
Here's how to do so using jQuery. The same technique can also be used for an ASP.NET DropDownList without causing a postback.


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


        $("#Button1").click(function() {


            $('#Select1').append($("<option>" + $('#Text1').val() + "</option>"));


            return false;


        });


    });    


</script>


</head>


<body>


<form id="form1" runat="server">


<div>


    <select id="Select1" name="Select1">


        <option>Option1</option>


        <option>Option2</option>


        <option>Option3</option>


        <option>Option4</option>


    </select>


    <input id="Text1" type="text" />


    <input id="Button1" type="submit" value="button" />


</div>


 


</form>


</body>


</html>


Scroll a page automatically to a specific position using jQuery

If you have a requirement where you want to scroll your page to a certain position with animation, then here's a single line of jQuery code that does that:


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


                $('html, body').animate({ scrollTop: 850 }, 'slow');


    });    


</script>


</head>


<body>


<form id="form1" runat="server">


<div>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


<p>Lorel Ipsum Lorel Ipsum Lorel Ipsum.</p>


</div>


</form>


</body>


</html>


Loop through all the rows in all the pages of an ASP.NET GridView

One simple way to loop through all the rows in all the pages of a GridView is to access its DataSource. Shown here is the code of how to do so:

C#


    protected void Button1_Click(object sender, EventArgs e)


    {


        DataSourceSelectArguments dsaArgs = new DataSourceSelectArguments();


        DataView view = (DataView)SqlDataSource1.Select(dsaArgs);


        DataTable dt = view.ToTable();


        for (int i = 0; i < dt.Rows.Count; i++)


        {


            for (int j = 0; j < dt.Columns.Count; j++)


            {


                string s = dt.Rows[i][j].ToString();


            }


        }


    }




VB.NET


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)


        Dim dsaArgs As DataSourceSelectArguments = New DataSourceSelectArguments()


        Dim view As DataView = CType(SqlDataSource1.Select(dsaArgs), DataView)


        Dim dt As DataTable = view.ToTable()


        For i As Integer = 0 To dt.Rows.Count - 1


            For j As Integer = 0 To dt.Columns.Count - 1


                Dim s As String = dt.Rows(i)(j).ToString()


            Next j


        Next i


    End Sub




Note: SqlDataSource1.Select(args) will make a call to the db every time it is accessed.

Check/UnCheck A RadioButton based on a CheckBox value using jQuery

The title is as amusing as the request I got recently from one of the users. He had a requirement where he had to Check/Uncheck or Select/Deselect an ASP.NET RadioButton based on the value of another ASP.NET CheckBox using client side code. I suggested him to do it using jQuery. The same solution will also work for HTML controls too. Here's how:


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


        $('#CheckBox1').click(


             function() {


                 $("input[type='radio']").attr('checked',


                 $('#CheckBox1').is(':checked'));


             });


    });


 


</script>


</head>


<body>


    <form id="form1" runat="server">


    <div>


        <asp:RadioButton ID="RadioButton1" runat="server" Checked="false" Text="UnCheckMe" />


        <asp:CheckBox ID="CheckBox1" runat="server" Text="ChkUnChkRadio" />


    </div>


    </form>


</body>


</html>


List the Drives on your Computer using C# or VB.NET

If you want to create a program to provide information about your Computer Drive, then use the System.IO.DriveInfo class. The DriveInfo class can be used to determine the drives available on your computer, drive capacity, free space, type of drives etc. as shown below:

C#


// Add namespace System.IO;


DriveInfo[] myDrives = DriveInfo.GetDrives();


foreach (DriveInfo di in myDrives)


{                


    Console.WriteLine(di.Name);


    if (di.IsReady)


    {


        Console.WriteLine(di.TotalSize);


        Console.WriteLine(di.DriveFormat);


        Console.WriteLine(di.AvailableFreeSpace);


        Console.WriteLine(di.TotalFreeSpace);


        Console.WriteLine(di.DriveType);


        Console.WriteLine(di.VolumeLabel);


    }


}




VB.NET


    ' Add namespace System.IO;


    Dim myDrives() As DriveInfo = DriveInfo.GetDrives()


    For Each di As DriveInfo In myDrives


        Console.WriteLine(di.Name)


        If di.IsReady Then


            Console.WriteLine(di.TotalSize)


            Console.WriteLine(di.DriveFormat)


            Console.WriteLine(di.AvailableFreeSpace)


            Console.WriteLine(di.TotalFreeSpace)


            Console.WriteLine(di.DriveType)


            Console.WriteLine(di.VolumeLabel)


        End If


    Next di


How to quickly add a Key Up Event to all TextBoxes in an ASP.NET GridView or Table control

The quickest way to add the KeyUp event to all textboxes in a HTML Table or ASP.NET GridView control is to use jQuery. Here's how


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script type="text/javascript">


$(document).ready(function() {


$("#GridView1 tr :text").keyup(function() {


alert('');


});


});


</script>


</head>




Here we are assuming that the table has an Id like this <table id="GridView1"> Also remember that the ASP.NET GridView renders as a table

If you haven't downloaded the latest version of jQuery yet, here are some links:

Latest jQuery and jQuery UI Theme links on Google CDN

Core ASP.NET Refcard - Commonly used core features and controls

Another valuable resource for developers from DZone! Dzone has released another Refcard with the most commonly used core functions and controls in ASP.NET. Written by Holger Schwichtenberg, this refcard showcases some very common and useful ASP.NET stuff.

Learn how to set up your ASP.NET development environment, understand the Webform model and common WebControls for Lists and Validation. The author also explores ASP.NET state management features, configuration file management and shows the typical content of an .aspx page.

You can download this handy Refcard from here.

Handling events of Control's inside ASP.NET ListView

A user recently asked me on the forums that he has a LinkButton kept inside a ListView that displayed the ProductNames. When a user clicks on the LinkButton, he should get the ProductID in codebehind to retrieve other details. Here's a quick and dirty way of how to do so by handling the OnItemCommand event of the ListView control


<asp:ListView ID="lvProducts" runat="server" DataSourceID="SqlDataSource1"


OnItemCommand="lvProducts_ItemCommand" ItemPlaceholderID="PlaceHolder1">


 <LayoutTemplate>


        <asp:Placeholder


        id="PlaceHolder1"


        runat="server" />


    </LayoutTemplate>


<ItemTemplate>


    <asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("ProductID") %>'


    Text='<%# Eval("ProductName") %>' CommandName="View Details"


    runat="server"></asp:LinkButton><br />


</ItemTemplate>


</asp:ListView>


<asp:SqlDataSource ID="SqlDataSource1" runat="server"


    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"


    SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">


</asp:SqlDataSource>





C#


protected void lvProducts_ItemCommand(object sender, ListViewCommandEventArgs e)


{


    if (e.CommandName == "View Details")


    {


        int productId = (int)e.CommandArgument;


    }


}




VB.NET


    Protected Sub lvProducts_ItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs)


        If e.CommandName = "View Details" Then


            Dim productId As Integer = CInt(e.CommandArgument)


        End If


    End Sub


Email BooBoo? Correct it with the new 'Undo' Feature in GMail

The 'Undo' feature in Gmail is awesome! What does it do? Well read on.

Let us say you typed your mail and hit the 'Send' button marking the wrong person in the mail. Gone is Gone! But now with a grace period of 5 seconds to rectify your BooBoo, it might well be just the right thing to save an Oops!

Google says the
Undo feature will give yourself a grace period of a few seconds to cancel sending, then edit your message before sending again. This feature can't pull back an email that's already gone; it just holds your message for five seconds so you have a chance to hit the panic button. And don't worry – if you close Gmail or your browser crashes in those few seconds, we'll still send your message.


To enable this feature, Open your Gmail > On the Top right Corner click 'Settings' > Click on the 'Labs' tab and find the 'Undo Send' feature. Enable it.



You can check out some other cool new features in What's New in Gmail?. Gmail is kind!

How to Add a Total Column to the ASP.NET ListView

A very frequently asked question about the ASP.NET ListView control is to display the sum of a column containing numeric data. In this post, I will show you how to quickly add a total's column to the ListView control. Here's how to do so by handling the ItemDataBound and PreRender event of the ListView

In your web.config, I have added a ConnectionString as shown below:


  <connectionStrings>


    <add name="NorthwindConnectionString"


         connectionString="Data Source=(local);


         Initial Catalog=Northwind;


         Integrated Security=True"


         providerName="System.Data.SqlClient"/>


  </connectionStrings>




HTML Markup


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


    <title></title>


</head>


<body>


    <form id="form1" runat="server">


    <div>


<asp:ListView ID="lvProducts" runat="server" DataSourceID="SqlDataSource1"


OnItemDataBound="lvProducts_DataBound" OnPreRender="lvProducts_PreRender"


ItemPlaceholderID="PlaceHolder1">


 <LayoutTemplate>


        <asp:Placeholder


        id="PlaceHolder1"


        runat="server" />


        Total: <asp:Label ID="lblTotal" runat="server" Text="Total"/>        


    </LayoutTemplate>


<ItemTemplate>


    <asp:Label ID="lblProductName" runat="server"


    Text='<%# Eval("ProductName") %>'/>


    <asp:Label ID="lblUnitPrice"


    Text='<%# Eval("UnitPrice") %>' runat="server"/><br />


</ItemTemplate>


</asp:ListView>


<asp:SqlDataSource ID="SqlDataSource1" runat="server"


    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"


    SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">


</asp:SqlDataSource>


 


    </div>


    </form>


</body>


</html>




C#


double totl = 0;


 


protected void lvProducts_DataBound(object sender, ListViewItemEventArgs e)


{


    if (e.Item.ItemType == ListViewItemType.DataItem)


    {


        Label lblUP = e.Item.FindControl("lblUnitPrice") as Label;


        totl += Convert.ToDouble(lblUP.Text);


    }


}


 


protected void lvProducts_PreRender(object sender, EventArgs e)


{


    Label lblTot = this.lvProducts.FindControl("lblTotal") as Label;


    lblTot.Text = totl.ToString(); ;


}





VB.NET


    Private totl As Double = 0


 


    Protected Sub lvProducts_DataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs)


        If e.Item.ItemType = ListViewItemType.DataItem Then


            Dim lblUP As Label = TryCast(e.Item.FindControl("lblUnitPrice"), Label)


            totl += Convert.ToDouble(lblUP.Text)


        End If


    End Sub


 


    Protected Sub lvProducts_PreRender(ByVal sender As Object, ByVal e As EventArgs)


        Dim lblTot As Label = TryCast(Me.lvProducts.FindControl("lblTotal"), Label)


        lblTot.Text = totl.ToString()


 


    End Sub


Accept dd/mm/yyyy date format in ASP.NET AJAX MaskedEditExtender

A simple way to use the dd/mm/yyyy date format in the ASP.NET AJAX MaskedEditExtender is to use a culturename in the extender that supports this format. Shown below is an example which accepts the date in dd/mm/yyyy format and also use a MaskedEditValidator for a date field. The CultureName used here is of Great Britain "en-GB"


<asp:ScriptManager ID="ScriptManager1" runat="server">


</asp:ScriptManager>


<asp:TextBox ID="txtDate" runat="server" ValidationGroup="DtVal"/>      


<cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server"


    CultureName="en-GB" TargetControlID="txtDate"


    Mask="99/99/9999" MaskType="Date" AcceptNegative="None"/> 


<cc1:MaskedEditValidator id="MaskedEditValidator1" runat="server"


    ControlExtender="MaskedEditExtender1"


    EmptyValueMessage="Please enter Date" InvalidValueMessage="Invalid Date"


    ControlToValidate="txtDate" ValidationGroup="DtVal" />  


Compare Two List of Strings in C# and VB.NET

Imagine you have two List<String>. You want to quickly compare them to see if all the elements match each other. Here's how to do so:

C#


List<string> strList1 = new List<string>


{


    "Jack", "And", "Jill", "Went", "Up", "The", "Hill"


};


 


List<string> strList2 = new List<string>


{


    "Jack", "And", "Jill", "Went", "Down", "The", "Hill"


};


 


bool result = strList1.SequenceEqual(strList2);




VB.NET


        Dim strList1 As List(Of String) = New List(Of String)(New String() _


        {"Jack", "And", "Jill", "Went", "Up", "The", "Hill"})


 


        Dim strList2 As List(Of String) = New List(Of String)(New String() _


         {"Jack", "And", "Jill", "Went", "Down", "The", "Hill"})


 


        Dim result As Boolean = strList1.SequenceEqual(strList2)




Remember that this search is case sensitive!

Mix09 Rocks! - Important Product and Technology Announcements at Mix09

Some important announcements were made at Mix 09, some of them we have been eagerly waiting for. Here's a quick tour of some annoucements made at Mix 09 and some links related to them:

Silverlight 3 - Most awaited! Check out the new features in the links given below

Silverlight 3 announced at Mix 09

All the New Features of Silverlight 3

What's New in Silverlight 3

Expression Blend 3 Preview - Compliments Silverlight 3!

First Look at Expression Blend 3

Expression Web 3 and Expression Web Super Preview - Announced by The 'Gu' (Scott Guthrie) with his pre-preps

Expression Web 3 and Super Preview

Expression Web Super Preview

ASP.NET MVC 1.0 RTW

ASP.NET MVC 1.0 RTW (Release to Web) Announced

ASP.NET MVC 1 with Phil Haack

Commerce Server 2009

Power of Commerce Server 2009

Web Platform Installer

Subtext 2.1.1 Available Via the Web Platform Installer

IIS Announcements at MIX 09

Check out a lot more at :

http://visitmix.com/Search?Tag=MIX09

http://on10.net/blogs/sarahintampa/Microsoft-Web-Technology-Announcements-from-MIX09/

A Lap Around MIX09 Annoucements

After recieving the NDA share of annoucements at the MVP Summit 09, and now with the annoucements at MIX09, I can only say that I am overwhelmed! Go Techie Go!

Determine if an object implements IEnumerable of (T)

I was recently attending a .NET conference when a programmer popped up a question. How do I make sure that my type implements IEnumerable<T>

Here's how:

C#


    protected void CheckInterfaceImpl(Type someType)


    {


        Type[] listInterfaces = someType.GetType().GetInterfaces();


        foreach (Type t in listInterfaces)


        {


            if (t.GetGenericTypeDefinition() == typeof(IEnumerable<>))   


            {       


                // Implements IEnumerable<T>


            }


            else


            {


                // Does not Implement IEnumerable<T>


            }


 


        }


    }




VB.NET


    Protected Sub CheckInterfaceImpl(ByVal someType As Type)


        Dim listInterfaces() As Type = someType.GetType.GetInterfaces()


        For Each t As Type In listInterfaces


            If t.GetGenericTypeDefinition() Is GetType(IEnumerable(Of )) Then


                ' Implements IEnumerable<T>


            Else


                ' Does not Implement IEnumerable<T>


            End If


 


        Next t


    End Sub




Know a better way? Share it here. I am all ears!

Access Session Variables in an ASP.NET Custom HttpHandler

If session state is required in your HTTP handler, you need to implement the IRequiresSessionState interface.

The IRequiresSessionState is a marker interface which is empty without any methods or elements in it and gives read/write access to Sessions. A Marker interface like this one just informs the runtime that a certain feature is to be enabled.

On the other hand, if you require only a read only access to Session, use the IReadOnlySessionState which is also a marker interface.

C#


public class MyHandler : IHttpHandler, IRequiresSessionState


{


    //  Use Session now


}




VB.NET


Public Class MyHandler


    Implements IHttpHandler, IRequiresSessionState


    '  Use Session now


End Class


Opening a new window from code behind on Button Click in ASP.NET

If you are looking out for server side code to open a new window on Button Click, then here's how to do so.

Add the following script to the <head> section of your page


<script language="javascript" type="text/javascript">


        function openNewWin(url) {


            var x = window.open(url, 'mynewwin', 'width=600,height=600,toolbar=1');


            x.focus();


        }


</script>




Then add a Button Control in the following manner


    <asp:Button ID="btnOpenPop" runat="server" Text="Open Pop"           


        onclick="btnOpenPop_Click" />




Finally add some code in the code behind file

C#


    protected void btnOpenPop_Click(object sender, EventArgs e)


    {


        string url = "http://www.dotnetcurry.com";


        ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>openNewWin('" + url + "')</script>");


    }




VB.NET


    Protected Sub btnOpenPop_Click(ByVal sender As Object, ByVal e As EventArgs)


        Dim url As String = "http://www.dotnetcurry.com"


        ClientScript.RegisterStartupScript(Me.GetType(), "OpenWin", "<script>openNewWin('" & url & "')</script>")


    End Sub


WCF REST Starter Kit Preview 2‏

As on the site
"The WCF REST Starter Kit is a set of features, Visual Studio templates, samples and guidance that enable users to create REST style services using WCF. While the October release of the WCF REST Starter Kit focused on building server-side REST services, the Preview 2 release adds features to make client-side REST development easier. Chief among the new functionality included in Preview 2 is a new class that provides a staged pipeline model for requesting resources over the web. Using this new HTTP client class allows the developer to plug into the various stages of communication to handle custom authentication, caching, and fault handling outside of the client’s application logic."


The goal is to provide a toolset that simplifies building RESTful services today, and to take feedback from the developer community on the features provided in the WCF REST Starter Kit that will shape future REST capabilities in WCF in .NET 4.

You can download the kit from here

Kobe: Web 2.0 Service Development Resource Kit

If you have been thinking of architecting and implementing Web 2.0 applications and services using the Microsoft Platform, then here's the resource for you.

Microsoft has released Kobe: Web 2.0 Service Development Resource Kit and as mentioned on the site,
Kobe is targeted toward technology decision makers, hands-on solution architects, development managers, and developers in the aspiring web startups community and in enterprises and businesses looking to invest in new Web 2.0application/service development projects.


Check out this link for Documentation, Walkthroughs, Videos, Sample projects and much more

Windows Vista and Windows Server 2008 RC Service Pack 2

Windows Vista and Windows Server 2008 Release Candidate Service Pack 2 was released to the public through the Customer Preview Program last week. This release along with fixes to bugs also incorportates feedbacks submitted by customers and partners.

You can download the Service Pack 2 Release Candidate over here

A few other important links:

Frequently Asked Questions: Windows Server 2008 Service Pack 2 RC and Windows Vista Service Pack 2 RC

Release Notes, Deployment and Other things to know about this release

Hide the Selected Row in an ASP.NET GridView

In order to hide the selected row of a GridView, use this simple technique

C#


    protected void custGV_SelectedIndexChanged(object sender, EventArgs e)


    {


        custGV.Rows[custGV.SelectedIndex].Visible = false;


    }




VB.NET


    Protected Sub custGV_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)


        custGV.Rows(custGV.SelectedIndex).Visible = False


    End Sub


Free ASP.NET MVC Sample Application and EBook

Scott Gu has done it again! Well this time it is a Free Ebook that he is offering. The 185 page ebook is actually a chapter from the new Professional ASP.NET MVC 1.0 Wrox book that is due to be released soon. The chapter is all about a Step By Step sample application called NerdDinner.com built on ASP.NET MVC 1.0. What a great way to learn this new technology!

Here's some background on NerdDinner.com. ScottGu writes
Scott Hanselman has been hosting NerdDinners for years, and came up with the idea of building the tutorial around an application that facilitates this. He is also now hosting a live custom-skinned version of the application at www.nerddinner.com


Download the entire 185 page free chapter over here and the SourceCode with Unit Tests over here

How to refresh an ASP.NET GridView automatically at regular intervals

A common requirement is to refresh the GridView after regular intervals. ASP.NET contains the Timer control which comes in very handy to achieve such requirements. Here's how to do so:

Add the GridView and the Timer control inside an ASP.NET AJAX UpdatePanel as shown below :


<asp:UpdatePanel ID="UpdatePanel1" runat="server">


<ContentTemplate>


<asp:Timer ID="Timer1" runat="server" Interval="3600" ontick="Timer1_Tick"></asp:Timer>


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />


<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />


<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />


<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />


<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />


</Columns>


</asp:GridView>


</ContentTemplate>


</asp:UpdatePanel>




Then in the code behind, add the following code which refreshes the GridView after every minute

C#


protected void Timer1_Tick(object sender, EventArgs e)


{


GridView2.DataBind();


}




VB.NET


Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)


GridView2.DataBind()


End Sub