Wednesday, July 9, 2014

JQuery–find parent with partial div id

Let’s say you need to find a parent of a DIV and you know part of the DIV id. For example, you want to turn the background color blue of the parent of the div id=toolbarnav, which has a div id that starts with WebPartWPQ (use ^ to do this).  There are multiple divs on the page that have different variations of this ID, but only one will be the parent of toolbarnav.

HTML

<div id="y">I'm in the Y div
           <div id="WebPartWPQ4"> I'm in WebPartWPQ4 div </div>
       </div >       
      <div id="x">I'm in the x div
       <div id="WebPartWPQ3">
           <a href="">I'm in the WebPartWPQ3 div - my child is toolbarnav</a>
           <div >
             <div id="toolbarnav">I'm in toolbarnav div</div>        
           </div>
       </div>
      
       <div id="DivID">
         I'm in DivID
       </div>

JQuery Code

$(document).ready(function() {
   
if (!
$('#toolbarnav').parents("div[id^='WebPartWPQ']").hasClass('turnblue')
    )
{
    $('#toolbarnav').parents("div[id^='WebPartWPQ']").addClass('turnblue');
}
    else { $('#toolbarnav').parents("div[id^='WebPartWPQ']").removeClass('turnblue');}
   
});

 

image

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;
                }
            }
     }

Thursday, January 27, 2011

Get the Directory and Page Name

If you need to find the aspx page name (including the folder it's in, if applicable) use the AppRelativeCurrentExecutionFilePath property of the Http Request:
string filename=HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
This will return results like: ~/MyFolder/My.aspx   or ~/MyRootLevel.aspx

I found this at: http://www.west-wind.com/weblog/posts/132081.aspx

Thursday, January 13, 2011

Get Identity Value when Using Dynamic SQL

If you need to get an identity value when using dynamic sql use sp_executesql and an output parameter to accomplish this.  You're identity value ends up in the @identity variable.
declare
 @sqlstatement nvarchar(4000)
,@identity int
...
set @sqlstatement = '
insert into lp.' + @permittype +'PermitNumber
(dummy) values (''dummy'') select @identity = scope_identity()';

EXECUTE sp_executesql @sqlstatement, N'@identity INTEGER OUTPUT', @identity OUTPUT

This is a great article on dynamic sql and using variables:
http://www.kodyaz.com/articles/tsql-sp_executesql-with-output-parameters.aspx
and
http://www.sommarskog.se/dynamic_sql.html

Wednesday, January 5, 2011

Change Cursor to an Hourglass for Web Applications

To accomplish this on the web you'll need to call a javascript or use CSS. This is a javascript example. In your aspx page add this code in the header or above your content:

wrap it in a script tag

function hourglass()
{
document.body.style.cursor = "wait";
}
 
In your aspx.cs code behind add this C# code in your Page Load (obviously change the button name to match yours)
 
btnSubmit.Attributes.Add("onclick", "javascript: hourglass();");

In my example the page redirects to another page, so the cursor set itself back automatically, but you may need to set it back to "default" yourself.