Thursday, October 28, 2010

Set DataRow Values and Other ASP.NET GridView Tips

You can set DataRow values in two ways:
First, using a column name:
myDataRow["City"]= "London";

Or, using an index:
myDataRow[2] = "London";

Don't use ItemArray property to set values, it won't work.

Set Text Box Width in a GridView Bound Field:

Use ControlStyle properties:

<asp:BoundField... ControlStyle-Width="60px"/>

Change GridViewRow Appearance: 

There are different ways to change GridViewRow appearance. The approach I like involves using the GridViewRow Style property. On RowDataBound event use this:

if (e.Row.RowType == DataControlRowType.Footer)
 {                              
     e.Row.Style.Add("color", "#999999");
     e.Row.Style.Add("font-weight", "bold"); 
     ...

Did you know that you could pass data format string as a parameter to the ToString() method?

For example:
e.Row.Cells[1].Text = iTotal.ToString("F2")
The above format string specifies 2 decimal places in a numeric value.

Tuesday, October 26, 2010

Simple Linq to Object example without Casting

I found this discussion related to casting the result of a LINQ query to a static object at http://devlicio.us/blogs/derik_whittaker/archive/2008/02/22/simple-linq-to-object-example-with-casting.aspx Since it was not possible to post a comment I decided to write a blog entry on my blog.

The example given at the above page gives the following code:


List<Sport > sports = new List <Sport>();
sports.Add(new Sport { SportID = 1, Name = "Sport 1", Description = "Sport Desc 1" });
sports.Add(new Sport { SportID = 2, Name = "Sport 2", Description = "Sport Desc 2" });
sports.Add(new Sport { SportID = 3, Name = "Sport 3", Description = "Sport Desc 3" });
sports.Add(new Sport { SportID = 4, Name = "Sport 4", Description = "Sport Desc 4" });
sports.Add(new Sport { SportID = 5, Name = "Sport 5", Description = "Sport Desc 5" });

var query = from s in sports
         where s.Name == "Sport 2"
         select s;

Sport sport = (Sport)query.First();


I would like to note that you could rewrite the above statements using lambdas:

Sport sport = sports.Where(s => s.Name == "Sport 2").First();

No "casting" is required.