Referencing ASP.NET CheckBox Controls using strings and casting

May 22nd, 2007

Category: Code ModeASP.NET - I recently ported one of my older web ASP Application to a web ASP.NET Application which presented a few challenges along the way. One of these challenges was a need to manage a series of 30 check boxes within a form. This part of the application is used to manage user permissions, restricting what areas of the application individual users had access to.

The user permissions are stored in a database as a pipe (”|”) delimited string. when the page containing the form loads, the permission string is pulled from the database, and split into an array.

When loading a page, all the checkboxes that indicate a users permission need to be checked.

In good ol’e fashioned ASP, all the checkboxes in a form would be given the same “name” attribute, and a “value” attribute containing the permission string. When the page containing the form was loaded, a piece of client-side javascript would run and iterate through all the checkboxes. For each checkbox in the form, the script would then iterate through each permission array item and if the item matched the checkbox value attribute, the checkbox state would be set to “checked”.

ASP Form

<form name="permissions" method="post" action="process_page.asp">
 <table width="461" border="0" cellspacing="0" cellpadding="0">
 <tr>
  <td>
   <input type="checkbox" name="setPermission" value="user_add">Add</ br>
   <input type="checkbox" name="setPermission" value="user_manage" />Manage</ br>
   <input type="checkbox" name="setPermission" value="user_delete">Delete</ br>
   <input type="checkbox" name="setPermission" value="user_edit"> Edit</br>
   <input type="checkbox" name="setPermission" value="user_setVisibility" /> set visibility</br>
  </td>
  </tr>
 </table>
</form>

When the ASP page is submitted after altering user permissions (checking or unchecking boxes), server-side code gets the values of all the checked checkboxes using Request.Form(”Checkbox_name”) .value, converts it to a pipe (”|”) delimited string, and updates the database with the new delimited string.

When porting this to ASP.NET, we run into a problem when replacing the standard form checkboxes to ASP.NET CheckBox Controls. .Net CheckBox controls cannot have the same “name” attribute so we cannot access them as a group like we did in ASP. A workaround for this is to give each CheckBox Control an ID equal to the permission value.

ASP.NET Form

<form action="" method="post" name="CMSForm" id="CMSForm" runat="server">
 <table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
   <td class="p_text1" width="67">
    <asp:CheckBox ID="user_add" Text="Add" runat="server" cbValue="add_user"/>
    <asp:CheckBox ID="user_manage" Text='View/Manage' runat="server" cbValue="view_user_manager"/>
    <asp:CheckBox ID="user_delete" Text='Delete' runat="server" cbValue="del_user"/>
    <asp:CheckBox ID="user_edit" Text='Edit' runat="server" cbValue="edit_user"/>
    <asp:CheckBox ID="user_setVisibility" Text='Set Visibility' runat="server" cbValue="hide_show_user"/>
   </td>
  </tr>
 </table>
</form>

Now for the FUN.NET

Now instead of using a full block of client-side javascript and nested loops as we did in ASP, we can access the ASP.NET CheckBox Controls directly using a few lines of server-side code and Casting.

The key to this is the change from using a “value” attribute to contain the permission value to using the Control’s ID to contain the permission value. Because the permission values are stored and pulled from a database, and split into an array, each array item can also be used to reference the CheckBox Controls directly without having to loop through each control.

To set the checked state of the CheckBox controls, we loop through the permissions array and Cast the string as a CheckBox Control allowing us to access that specific control.

I am using a MySql database here:
First we need to get or data from the database. “access” is the DB table column that stores my permission string for each user.

MySqlConnection MyConString = new MySqlConnection(...your datababase connection string here...);
MySqlCommand myCommand = new MySqlCommand("SELECT  access FROM <your dataTable> WHERE emp_ID = <unique ID of user you want to manage> ", MyConString);
MyConString.Open();
MySqlDataReader dr = myCommand.ExecuteReader();

Next we get the string value of “access” and split it into an array.

try{
 dr.Read();
}
catch(Exception ex){
 however you want ot handle the exception here
}
char[] splitter  = {'|'};
string[] arrPermissions = dr["access"].ToString().Split(splitter);

setCheckboxes(arrPermissions);

setCheckboxes Method (this is where the magic happens)
This method takes the permissions array as a argument, iterates through the array, casting the string value of each item as a CheckBox, and sets the Checked state of all matching CheckBox Controls.

private void setCheckboxes(string[] arrPermissions)
{
foreach(string strPermission in arrPermissions){
((CheckBox)this.CMSForm.FindControl(strPermission)).Checked = true;
}
}

The same technique can be applied to other .NET controls as well to change their attributes, styles, or whatever.
I could have just as easily changed the text of the controls using something like: ((CheckBox)this.CMSForm.FindControl(strPermission)).Text= “I am a CheckBox Control”;

PHP - Break the Web Shackles!

May 10th, 2007

Code Mode IconOver the last couple years or so, my development focus has been on the .NET Framework and C# so, I’m sad to say, it’s been a while since I’ve written any “real” PHP code. I think the main reason for this is that I have been developing more and more desktop applications and less web applications. When I was writing web apps, I’d say my efforts were split pretty much down the middle between PHP and ASP. Then .NET came along with C# and I was hooked. I was able to continue to develop web apps but also transition to desktop development while using the same tools. C# definitely had an advantage here. But alas.. Read the rest of this entry »

Creating Application Shortcuts for Click-Once Applications

May 3rd, 2007

Category: Code ModeWhile writing my latest C# .NET software application, the need came to be able to allow users to enable and disable an “auto-start” feature. Users wanted to control whether the app would start automatically when they start their workstation, or log into their accounts, or whether they had to start it manually. The challenge came out the fact that this was a very small application and was being created using VS C# Express and Click-Once deployment. My options were to either manipulate the registry run keys, or create a method to create/delete an application shortcut in the startup folder. I opted for the shortcut solution figuring it was probably the safest and easiest solution (VS express editions have limited access to registry manipulation, not to mention that any keys created through the use of the application would be orphaned after uninstall). Read the rest of this entry »

New Picture Gallery Added

May 2nd, 2007

Category: PersonalI have set up a picture gallery where I will begin posting pictures of “stuff”… vacations, friends, family, etc..

The first album has been included and contains pictures of our recent vacation in Cabo Mexico.

I will continue to add pics and albums over the next few days/weeks and try to transfer existing albums from another gallery. You can check it out here:
www.edwardstafford.com/gallery1

In The Beginning…

April 30th, 2007

Well here it is. My first post to this blog. I just finished installing WordPress to my server after using Blogger for quite a while. Why the change? Well, I like having control over my own “stuff”. Don’t get me wrong. Blogger is a fine platform, but I prefer to have my things organized under the same roof and not have to manage a handful of different services across the web.

After searching for a new blogging solution, I looked at a number of different releases for both Windows/IIS and Linux/Apache platforms. I finally decided on WordPress for a number of reasons.

1. Support and stability - WordPress is a proven solution and has a large user base, which also means a lot of peer support.
2. Ease of use - It was easy to set up and ran on my server without any additional requirements.
3. Control - WordPress has built in controls for managing posts and comments, and they’re easy to use. I don’t have to fuss over design and (X)HTML if I don’t want to and still get a nice clean page. On the other hand, If I do want to get into altering page design and (X)HTML, I can do that to through the built-in CMS tools.
4. Organization - One of the features I like best is the categories. Categories allow me to organize posts into groups and categories/sub-categories making it easy to find the topics that interest you most.

All in all, The set up was actually pretty simple and I had a working blog in a matter of minutes. The next step is getting the layout and visual appeal to my liking.