The .NET blog

How to: Alternate row color with the ASP.NET Repeater control

April 2, 2009

The ASP.NET Repeater control is great in a whole range of scenarios. I use it all the time my self because it’s flexible and simple to use. Often, it’s for outputting rows of data, where I want to avoid using the GridView control, or simply because I don’t want it to be built as a table. In that case, I find my self wanting to apply a different color to every second row a lot of the time, to get an effect like this:

John Doe
Jane Doe
John Doe
Jane Doe

Microsoft offers a way to accomplish this with the repeater:

<asp:Repeater runat="server" ID="repData">
	<ItemTemplate>
		<div style="background-color: #fff;">
			<%# Container.DataItem.ToString() %>
		</div>
	</ItemTemplate>
	<AlternatingItemTemplate>
		<div style="background-color: silver;">
			<%# Container.DataItem.ToString() %>
		</div>
	</AlternatingItemTemplate>
</asp:Repeater>

Now, that’s just fine for such a simple example, but usually my repeater will contain way more markup. Having it in two separate places fills up my file and forces me to make modifications in two places instead of one. It’s simply not a very practical solution, especially not when considering that we’re doing all that to output a different background color. It’s time to get creative:

<asp:Repeater runat="server" ID="repData">
	<ItemTemplate>
		<div style="background-color: <%# GetRowColor() %>;">
			<%# Container.DataItem.ToString() %>
		</div>
	</ItemTemplate>
</asp:Repeater>

As you can see, instead of outputting the color directly, we make a call to a function called GetRowColor(). It should be implemented in your CodeBehind file like this:

private int counter = 0;
protected string GetRowColor()
{
	if(counter++ % 2 == 0)
		return "#fff";
	else
		return "silver";
}

If you’re new to C#, you might wonder what that function does, but in fact, it’s quite simple. We have a counter variable, and each time the GetRowColor() method is called, we increment that variable (counter++ is the same as counter = counter + 1). We then use the modulo operator (%) to test if the number is an equal number or not – if it is, we return one color, and if it’s not, we return another color. This ensures that every other row is rendered with another background color.

Now, in a real life example, you might want to output the color choice another way. For instance, you could have an “even” and an “odd” CSS class to use each time you want even and odd rows, allowing you to define the color in one common place. Or perhaps you only want the style declaration on odd rows, letting equal rows default to the parent background color? No problem, just change the GetRowColor() method into something else and use it accordingly.

Filed under: ASP.NET,C# — admin @ 11:43 am

How to: Download a file from the Internet with C#

March 16, 2009

With .NET, working with remote files are very easy. From the System.Net namespace, we get several classes which comes in handy for doing just that. For instance, downloading a file to your computer can be accomplished with a few lines of code, using the WebClient class:

try
{
	WebClient webClient = new WebClient();
	webClient.DownloadFile("http://www.google.com/intl/en_ALL/images/logo.gif", @"c:\google_logo.gif");
}
catch(Exception ex)
{
	Console.WriteLine("Could not download file: " + ex.Message);
}

Besides the exception handling, downloading a file, in this case an image, is a two-line job. However, by doing it like this, we will be blocking the application completely while downloading the file. If you have to download larger files than a simple logo, you should definitely do it asynchronously. Fortunately for us, the WebClient class supports this right out of the box. But hey, wouldn’t it be cool if we could somehow see the status of the download in progress? No problem, WebClient can do that too. Here’s a complete example:

using System;
using System.Text;
using System.Net;
using System.ComponentModel;

namespace WebClientDemo
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				WebClient webClient = new WebClient();
				webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
				webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
				webClient.DownloadFileAsync(new Uri("http://upload.wikimedia.org/wikipedia/en/2/2e/STS-95_Florida_From_Space.jpg"), @"c:\STS-95_Florida_From_Space.jpg");
				Console.ReadKey();
			}
			catch(Exception ex)
			{
				Console.WriteLine("Could not download file: " + ex.Message);
			}
		}

		static void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
		{
			Console.WriteLine(String.Format("{0} of {1} bytes downloaded ({2}% done)", e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage));
		}

		static void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
		{
			if(e.Error == null)
				Console.WriteLine("All done downloading the file!");
			else
				Console.WriteLine("Could not download file: " + e.Error.Message);
		}
	}
}

We’re downloading a large image from Wikipedia, and as you will see, progress is written to the console. You can obviously fine tune this a bit – for instance, you might want to limit how often progress is written out, but besides that, it’s working pretty decent, and with a pretty limited amount of code. This is a console application, so there’s not that much need for doing stuff asynchronously, but for a WinForms application, doing stuff like this on a separate thread can be really important. If not for a more responsive UI, then at least for being able to report progress while downloading.

If you want direct access to the data being downloaded, without saving to a file first, you should have a look at the DownloadData() method, which returns a byte array, or the DownloadString() method, which downloads the file and returns a string representation of the content (mostly usable for plaintext files, obviously). Both have an asynchronous version too. Enjoy :)

Filed under: ASP.NET,C# — admin @ 10:14 pm

Microsoft releases free chart controls

December 1, 2008

In case you haven’t noticed it yet, Microsoft has just released a set of Chart controls to be used with both ASP.NET and WinForms applications. They support both 2D and 3D charts, and has a bunch of cool features, which should cover most of your charting needs :) . They can be downloaded from this page and Scott Guthrie from Microsoft has a more detailed post about the ASP.NET aspects of it here. Enjoy :)

Filed under: AJAX.NET,ASP.NET,C#,General — admin @ 6:13 pm



© net-tutorials.com 2006 - 2012