Thursday, February 07, 2008

asp.net 2.0 Roles DropDownList Control in C#

Translation of this post to french at :
http://s4n44.blogspot.com/2008/02/aspnet-20-dropdownlist-de-rles-enc.html

This is a user control, which encapsulates a DropDownList, an ObjectDataSource and custom, simplified roles class. The user control will connect automatically (of course), with the aspnetdb database pointed to in the web.config
for vb.net users, here's a nice converter provided by Telerik (http://www.telerik.com ) :
http://www.codechanger.com/

Here's the code for the user control :

<%@ Control Language="C#" AutoEventWireup="true" CodeFile=" ddlRoles.ascx.cs" Inherits="RoleControl" %>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="sourceRoles" DataTextField="RoleName"
DataValueField="RoleName" Width="185px">
</asp:DropDownList>
<asp:ObjectDataSource ID="sourceRoles" runat="server" SelectMethod="GetRoles"
TypeName="CustomRoles"></asp:ObjectDataSource>


Code behind for the user control:


using System;

public partial class RoleControl : System.Web.UI.UserControl
{
public String SelectedValue
{
get { return this.DropDownList1.SelectedValue; }
set { this.DropDownList1.SelectedValue = value; }
}
}


The object datasource uses the class below :


using System;
using System.Web.Security;
using System.Collections.Generic;

public class CustomRoles
{
private string mRoleName;

public string RoleName
{
get { return mRoleName; }
set { mRoleName = value; }
}

/// <summary>
/// this function, loops through all roles in the database, and builds
/// a collection of CustomRoles instances into a generic list of CustomRoles
/// then we return the list as the source for the dropdown.
/// The RoleName property is used to bind the datavaluefield and datatextfield
/// in the dropdownlist
/// </summary>
/// <returns></returns>
public List<CustomRoles> GetRoles()
{
//getroles
string[] roleslist = Roles.GetAllRoles();

int i = 0;
//instance of customroles
CustomRoles br;

//create the list (or collection of CustomRoles instances)
List<CustomRoles> lstbr = new List<CustomRoles>();

//fill the list by looping through the array of strings
foreach (string brole in roleslist)
{
br = new CustomRoles();
br.RoleName = brole;
lstbr.Add(br);
}

return lstbr;

}

}


Comments are welcome !

2 comments:

RRave said...

Dear Sir,

I have a launched new web site for .NET programming resources. www.codegain.com. I would like to invite to the codegain.com as author and supporter. I hope you will joins with us soon.

Thank You
RRaveen
Founder www.codegain.com

r4i said...

THANKS BUDDY FOR SHARING CODE. and the website is really awesome.......