Tuesday, October 25, 2011

Check if GridView Column Exists

If you have a DataRowView you can use the following extension method to check if a GridView column exists:

public static bool ColumnExists( this  DataRowView rowData,  string  fldToCheck)
{

return rowData.Row.Table.Columns.Contains(fldToCheck);
}

Normally, you would use it on RowDataBound event, e.g:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

DataRowView rowData = e.Row.DataItem as DataRowView;
string  fldToCheck = "MyFieldName";
if (e.Row.RowType == DataControlRowType.DataRow)
{
      if (rowData.ColumnExists(fldToCheck) ...


Related posts:
Find GridView Column Index
Set DataRow Values and Other ASP.NET GridView Tips


Monday, October 17, 2011

Modify Query String


If you build a hyperlink on a web page dynamically, sometimes you may need to append or modify an existing query string.
To modify a url with an existing query string, first grab the AbsoluteUrl property:

string path = Request.Url.AbsolutePath ;

This will give you a url wihout the query string portion.

If you need to reuse an existing portion of the query string, you have to get it yourself, e.g:

string key = Request.QueryString["key"];
string path = Request.Url.AbsolutePath + "?key="+ key;


Now, you can build your url:

string url  = path+ "&key2="+ myValue;

Related posts:
Add JavaScript Dynamically to ASP.NET UpdatePanel
Examine Columns in ASP.NET Dynamic Data MetaTable




Thursday, October 13, 2011

Find GridView Column Index

If you create GridView columns dynamically using the AutogenerateColumns = true feature, sometimes you need to find a column index from the column name.

I created an extension method to find a column index:

public static int GetIndex(this DataRowView tableData, string fieldName)
        {
            DataColumn dc = tableData.DataView.Table.Columns[fieldName];
            
            if (dc != null)
            {
                return dc.Ordinal;
            }
            return -1;
        }

This is how you call from the RowDataBound event handler:

DataRowView tableData = e.Row.DataItem as DataRowView;
int pos = tableData.GetIndex("MyFieldName");                
if (pos != -1){
   //do your thing
}

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:

if(Request.QueryString!= null && Request.QueryString.Count>0){
     //some piece of code.
}



Friday, December 3, 2010

C# Delegates as Method Parameters

Let's say you have 2 methods that go through similar steps:

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;
 }
 
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:
  delegate bool IsValid();
  delegate string GetItem();
Create a method that will use the delegates:

 private string GetMyItem(IsValid isValid, GetItem getItem)
 {
   if (isValid())
   {
        string item = getItem();
         SetEventProperties();
         return item;
   }
   else
       return null;
  }       
An alternative method signature is as follows:
 private string GetNavItem(Func<bool> isValid, Func<string> getItem)
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:
string strPrev =   GetMyItem(IsValidPrevEntry, GetPrevString);
string strNext =   GetMyItem(IsValidNextEntry, GetNextString);
An interesting discussion of delegates can be found on the stackflow.

Tuesday, November 16, 2010

Add JavaScript Dynamically to ASP.NET UpdatePanel

Use the following example:

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);}
           }}"
       );
ScriptManager.RegisterClientScriptBlock (this, this.GetType(), "ajax", sb.ToString(), true); 

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.