Monday, February 28, 2011

Adding Validation in a GridView

I’m doing two things in this example. Adding a javascript to force only certain keys allow during data entry, and adding a regular expression validator.  Depending on the type of data I have, I need a different validator for each row in the grid (or none).
First: setup your validator in your grid template:
<asp:TemplateField HeaderText="Contact Data">
<ItemTemplate>                   
<asp:TextBox  id="contactdata" Text="" runat="server"  /> 
<asp:RegularExpressionValidator ID="ValidateContactData" SetFocusOnError="true" 
runat="server"  CssClass="formerrorsmall"  
ErrorMessage="Invalid format! " 
ControlToValidate="contactdata" />    
</ItemTemplate> 
</asp:TemplateField> 
The method is called from the row data bound for the gridview but it could go into the row data bound method itself –I was just reusing it across multiple row data bounds!
//lo contacts not assigned
protected void gvLOContactsNotAssigned_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{   
AddValidations(sender, e);
}
….

//add the validation expressions and javascripts
//use a method b/c we'll use this for both contact grids
protected void AddValidations(object sender, GridViewRowEventArgs e)
{
//find contact type
TextBox tbContactType = (TextBox)e.Row.FindControl("ContactType");
TextBox contactdata = (TextBox)e.Row.FindControl("contactdata");
//is this a phone?
TextBox tbIsPhone = (TextBox)e.Row.FindControl("IsPhone");
 
//if it's an email or a phone - add validator
if (tbContactType.Text == "EMAIL" || tbIsPhone.Text == "T")
{
RegularExpressionValidator rev = (RegularExpressionValidator)e.Row.FindControl("ValidateContactData");
 
//if its a phone add validator
if (tbIsPhone.Text == "T")
{
rev.ValidationExpression = "\\(\\d{3}\\) \\d{3}\\-\\d{4}";
//add js for the type of contact
contactdata.Attributes.Add("onKeyPress", "return PhoneOnly(this, event); ");
 
}
else if (tbContactType.Text == "EMAIL")
{
rev.ValidationExpression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
}
}
 
if (tbContactType.Text == "CONTACT") //it's required
{
Label lblRequired = (Label)e.Row.FindControl("lblContactRequired");
lblRequired.Visible = true;
}
}

GridView Footer Spanning Columns

To add a footer to your Gridview you can use this code.  I’ve seen other samples that “deleted” the columns, but I couldn’t get those to work (they hung off the side still visible)!
protected void gvLOContactsNotAssigned_RowDataBound(object sender, GridViewRowEventArgs e)
       {
           if (e.Row.RowType == DataControlRowType.DataRow)
           {  
               AddValidations(sender, e);
           }
           else if (e.Row.RowType == DataControlRowType.Footer)
           {
               e.Row.Cells[0].Text = "* Contact Phone is required";
               //how many cells?
               int cols = e.Row.Cells.Count;
               for (int i = 0; i < cols; i++)
               {
                   //remove all but the first (0)
                   if (i != 0)
                   {
                       e.Row.Cells[i].Visible = false;
                   }
               }
               //span the length of the other cells
               e.Row.Cells[0].ColumnSpan = cols;
           }
       }

Monday, February 14, 2011

Looping Through GridView Rows

example: loop through all the rows and turn on / off link buttons if the user does not have a specific role
string role = Session["roleName"].ToString();
foreach (GridViewRow row in gvApplication.Rows)
{
           LinkButton lbUpdate = (LinkButton)row.FindControl("Update");
            LinkButton lbDelete = (LinkButton)row.FindControl("Delete");
            try
            {
                if (role == "SUPERUSER" || role == "ADMINISTRATOR")
                {
                    lbUpdate.Enabled = true;
                    lbDelete.Enabled = true;
                }
                else
                {
                    lbUpdate.Enabled = false;
                    lbDelete.Enabled = false;
                }
            }
     }