if(Request.QueryString!= null && Request.QueryString.Count>0){
//some piece of code.
}Thursday, March 17, 2011
Check QueryString for Null
If you need to determine whether the Request.QueryString is null and take some action depending on the result, it is not enough to check for null. QueryString is an HttpValueCollection type, so even if the Request.Url does not have a query string appended to it, the value of the collection is not going to be null. The proper way to check if the query string contains anything is to check for null and the Count property as well:
Friday, December 3, 2010
C# Delegates as Method Parameters
Let's say you have 2 methods that go through similar steps:
These 2 methods essentially do the same thing. First, they check for some condition, and if the condition evaluates to true, they call another method, set some properties, and return a string. We can use C# delegates to refactor these 2 methods into one. Here is how you do it:
Declare 2 delegates whose signature matches the methods we want to replace:
Create a method that will use the delegates:
An alternative method signature is as follows:
This way we don't have to declare delegates separately.
Now, we can call the new method, passing the methods that we called before refactoring, as parameters:
An interesting discussion of delegates can be found on the stackflow.
public string GetPrevItem()
{
if (IsValidPrevEntry())
{
string item = GetPrevString();
SetProperties();
return item;
}
else
return null;
}
public string GetNextItem()
{
if (IsValidNextEntry())
{
string item = GetNextString();
SetProperties();
return item;
}
else
return null;
}
Declare 2 delegates whose signature matches the methods we want to replace:
delegate bool IsValid();
delegate string GetItem();
private string GetMyItem(IsValid isValid, GetItem getItem)
{
if (isValid())
{
string item = getItem();
SetEventProperties();
return item;
}
else
return null;
}
private string GetNavItem(Func<bool> isValid, Func<string> getItem)
Now, we can call the new method, passing the methods that we called before refactoring, as parameters:
string strPrev = GetMyItem(IsValidPrevEntry, GetPrevString);
string strNext = GetMyItem(IsValidNextEntry, GetNextString);
Tuesday, November 16, 2010
Add JavaScript Dynamically to ASP.NET UpdatePanel
Use the following example:
What it does is attaches a JavaScript function (defined elsewhere) to each input box on the page on the key press event, and then registers it for use with a control that is inside an UpdatePanel. This could be used for user input validation. The code has been verified in IE and Firefox.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@" var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text') {
inputs[i].onkeypress = function (event) {
event = event || window.event;
return myJavaScriptFunction(event);}
event = event || window.event;
return myJavaScriptFunction(event);}
}}"
);
What it does is attaches a JavaScript function (defined elsewhere) to each input box on the page on the key press event, and then registers it for use with a control that is inside an UpdatePanel. This could be used for user input validation. The code has been verified in IE and Firefox.
Wednesday, November 10, 2010
ASP.NET GridView Subclass with Dynamic Footer Totals
A frequent requirement when using an ASP.NET GridView on a web page is to have a footer with totals for numeric columns in the GridView. Here is a GridView subclass that calculates footer totals dynamically. It requires 3 parameters:
FirstComputedColumnIndex - the for index of the first column in the data set to be computed
FirstVisbleComputedColumnIndex - for the index of the first computed column to be shown
NumberOfComputedColumns - for the number of computed columns.
Here is the class code:
The Indexer class can be nested within the GridView subclass.
The last example shows how to use the custom GridView on a ASP.NET web page:
First, use the register tag:
<%@ Register Namespace="Eric.TotalGrid" TagPrefix="x" Assembly="TotalGrid" %>
Then, use it just like any other GridView:
<x:GridView runat="server" ....
FirstComputedColumnIndex="4" FirstVisbleComputedColumnIndex="3" NumberOfComputedColumns="10" >
FirstComputedColumnIndex - the for index of the first column in the data set to be computed
FirstVisbleComputedColumnIndex - for the index of the first computed column to be shown
NumberOfComputedColumns - for the number of computed columns.
Here is the class code:
namespace Eric.TotalGrid {
public partial class GridView : System.Web.UI.WebControls.GridView
{
private Indexer footerTotals;
public int FirstComputedColumnIndex { get; set; }
public int FirstVisbleComputedColumnIndex { get; set; }
public int NumberOfComputedColumns { get; set; }
protected override void OnLoad(EventArgs e)
{
ShowFooter = true;
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
footerTotals = new Indexer(NumberOfComputedColumns);
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.RowDataBound += new GridViewRowEventHandler(this.GridView1_RowDataBound);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView tableData = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = FirstComputedColumnIndex; i < (FirstComputedColumnIndex + NumberOfComputedColumns); i++)
{
if (tableData[i] != DBNull.Value)
{
decimal result = 0;
if (Decimal.TryParse(tableData[i].ToString(), out result))
{
footerTotals[i - FirstComputedColumnIndex] += result;
}
}
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
for (int i = 0; i < NumberOfComputedColumns; i++)
{
if (e.Row.Cells.Count > (i + FirstVisbleComputedColumnIndex))
e.Row.Cells[i + FirstVisbleComputedColumnIndex].Text = footerTotals[i].ToString();
}
}
}
}
The key to this GridView is using an Indexer class that can be accessed like an array. Here is its listing:
}
The key to this GridView is using an Indexer class that can be accessed like an array. Here is its listing:
class Indexer
{
private int _upperLimit;
private decimal[] myArray;
public Indexer(int limit)
{
_upperLimit = limit;
myArray = new decimal[_upperLimit];
}
public decimal this[int index] // Indexer declaration
{
get
{
// Check the index limits.
if (index < 0 || index >= _upperLimit)
return 0;
else
return myArray[index];
}
set
{
if (!(index < 0 || index >= _upperLimit))
myArray[index] = value;
}
}
}
The last example shows how to use the custom GridView on a ASP.NET web page:
First, use the register tag:
<%@ Register Namespace="Eric.TotalGrid" TagPrefix="x" Assembly="TotalGrid" %>
Then, use it just like any other GridView:
<x:GridView runat="server" ....
FirstComputedColumnIndex="4" FirstVisbleComputedColumnIndex="3" NumberOfComputedColumns="10" >
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.
<asp:BoundField... ControlStyle-Width="60px"/>
There are different ways to change GridViewRow appearance. The approach I like involves using the GridViewRow Style property. On RowDataBound event use this:
Did you know that you could pass data format string as a parameter to the ToString() method?
For example:
The above format string specifies 2 decimal places in a numeric value.
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")
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:
I would like to note that you could rewrite the above statements using lambdas:
No "casting" is required.
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.
Tuesday, August 3, 2010
Resize WinForm Controls Automatically
Let' say you have a form with a ListBox and OK and Cancel buttons.
You want controls to be resized automatically when a form is resized. This is how you can achieve this by using the Anchor property:
Place all controls inside a GroupBox. Set the Anchor and Dock properties
GroupBox properties:
Anchor : Top, Bottom, Left, Right
Dock : None
Buttons properties:
Anchor : Bottom, Right
Dock : None
ListBox properties:
Anchor : Top, Bottom, Left, Right
Dock : None
You want controls to be resized automatically when a form is resized. This is how you can achieve this by using the Anchor property:
Place all controls inside a GroupBox. Set the Anchor and Dock properties
GroupBox properties:
Anchor : Top, Bottom, Left, Right
Dock : None
Buttons properties:
Anchor : Bottom, Right
Dock : None
ListBox properties:
Anchor : Top, Bottom, Left, Right
Dock : None
Subscribe to:
Posts (Atom)