Bind enum to ddl

Sometime we need to bind the value and the name of the enum to the dropdownlist. here is the code that will help us to achieve this.

here I have created a method to convert enum into hashtable :

    public Hashtable ConvertEnumToHashTable(Type myenum)
    {
        string[] names = Enum.GetNames(myenum);
        Array values = Enum.GetValues(myenum);
        Hashtable ht = new Hashtable();
        for (int i = 0; i < names.Length; i++)
        {
            ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
        }
        return ht;
    }

Now here is code that shows you how to use this function :

    protected void Page_Load(object sender, EventArgs e)
    {
        Hashtable ht = ConvertEnumToHashTable(typeof(myenum));
        myDDL.DataSource = ht;
        myDDL.DataTextField = "value";
        myDDL.DataValueField = "key";

        myDDL.DataBind();

    }

Hope this code will help !!!

Jay Ganesh

About these ads

Sorting Table Columns with jQuery

Background

I always heard about sorting table data & read lots of article that explain how to achieve it using jquery. You will also find lots of plugins available for sorting table data like Table sorter, Flexigrid , jqGrid and many more. Along with sorting feature it also support many more features like paging, resizable columns, cool themes, search and many more… But I feel that there must be one more feature in this library to sort table columns so that user will have full flexibility by playing with table arrangement along with column data. It might be possible that some of the library support this features or if not then planning to add it in their upcoming releases..

Sample Code

This code consist of GridView which shows Employee Name as Column along with some data. Now when user press sort button column will be sorted in ascending order along with data.

Here I have tried to achieve this features using some of the jQuery code without need of any library. Only thing we need here is jQuery library.

Step 1 : Add jQuery file Reference inside the tag of the page

<script src="Js/jquery-1.4.2.js" type="text/javascript"></script>

Step 2 : Next we need to drag and drop gridview on the page & set AutoGenerateColumns property to false. Specify the ID of the grid “gvEmployees”.

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" Width="500">
   <Columns>
      <asp:BoundField DataField="Sandeep" HeaderText="Sandeep" />
      <asp:BoundField DataField="Nishar" HeaderText="Nishar" />
      <asp:BoundField DataField="Dharmik" HeaderText="Dharmik" />
      <asp:BoundField DataField="Ravi" HeaderText="Ravi" />
      <asp:BoundField DataField="Jigish" HeaderText="Jigish" />
      <asp:BoundField DataField="Kapil" HeaderText="Kapil" />
   </Columns>
</asp:GridView>

Step 3 : Drag and drop one button on the page and give its ID=”btnSortColumn” and Text=”Sort Column”.

<asp:Button ID="btnSortColumn" runat="server" Text="Sort Column" />

Step 4 : write jQuery script for the button click event, which will sort table column along with data.

       $('#btnSortColumn').click(function() {

            //Get all the rows of employee grid
            var rows = $('#gvEmployees tr');

            //Start sorting column along with data
            rows.eq(0).find('th').sort(function(a, b) {

                return $.text([a]) > $.text([b]) ? 1 : -1;

            }).each(function(new_Index) {

                //Original Index
                var original_Index = $(this).index();

                //Reorder Header Text
                rows.each(function() {
                    var th = $(this).find('th');
                    if (original_Index !== new_Index)
                        th.eq(original_Index).insertAfter(th.eq(new_Index));
                });

                //Reorder Column Data
                rows.each(function() {
                    var td = $(this).find('td');
                    if (original_Index !== new_Index)
                        td.eq(original_Index).insertAfter(td.eq(new_Index));
                });

            });
            return false;
        });

Code itself explain lots of things,

Here ‘rows’ variable contain collection of Employee row. Next we find out the column name using header tag (th) and call the sort function of javascript to call the sorting mechanism.

rows.eq(0).find('th').sort(function(a, b)
{
    return $.text([a]) > $.text([b]) ? 1 : -1;
})

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

  • Less than 0: Sort “a” to be a lower index than “b”
  • Zero: “a” and “b” should be considered equal, and no sorting performed
  • Greater than 0: Sort “b” to be a lower index than “a”

To sort an array numerically and ascending for example, the body of your function would look like this:

function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}
th.eq(original_Index).insertAfter(th.eq(new_Index));

Will insert every table header element ( th ) from original place to new place.

td.eq(original_Index).insertAfter(td.eq(new_Index));

Will insert every table data element ( td ) from original place to new place.

Step 5 : Now we have done with aspx page coding , but what about data filling logic. here it goes. Call data biding function of the gridview in Page Load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Sandeep");
        table.Columns.Add("Nishar");
        table.Columns.Add("Dharmik");
        table.Columns.Add("Ravi");
        table.Columns.Add("Jigish");
        table.Columns.Add("Kapil");
        table.Rows.Add("20", "25", "45", "33", "22", "12");
        table.Rows.Add("40", "15", "15", "13", "12", "40");

        gvEmployees.DataSource = table;
        gvEmployees.DataBind();
    }

Here i have created dynamic datatable & filled some data rather than making Database connection & fetch data. but you can do what ever you want to bind grid.

Step 6 : Everything is setup now just press F5 & see the output of the page.

Before Sorting Column

After Sorting Column

Browser Support

I have tested this code on Firefox 3.6.8 & IE 8. you can also test it on any browser, i am sure that this code will run on all the latest browser.

Hope this will help !!!

Jay Ganesh

Reference

http://www.javascriptkit.com/javatutors/arraysort.shtml
http://api.jquery.com/insertAfter/

Shout it

kick it on DotNetKicks.com

Visual Studio LightSwitch

Microsoft has announced a new product called Microsoft Visual Studio LightSwitch, which the company claims is the simplest way to build business applications for the desktop and cloud. LightSwitch is a new member of the Visual Studio family focused on making it easy to develop line-of-business applications.

What is LightSwitch?

Visual Studio LightSwitch includes pre-built templates and tools in a simplified development environment for building scalable custom business applications that connect with existing applications, legacy systems, and Web services. Developers can choose from a wide variety of hosting, deployment, and third-party plug-in options. Deployment is simplified in that applications (which are at their core Silverlight applications) can be deployed to the client, browser, and even Windows Azure (post-beta). LightSwitch can be used with C# or Visual Basic and it supports SQL Server, SQL Azure, SharePoint, and Microsoft Office.

LightSwitch dramatically decreases the time it takes to build a custom application by automatically handling routine code; it’s a rapid application development tool that offers application shells and screen templates to allow the developer to concentrate on the core business logic.

Security is an important aspect of any business application. LightSwitch provides authentication and authorization features that let you define users and roles. This prevents unauthorized access to sensitive data.

Extensibility features in LightSwitch let you change the appearance of your applications by applying themes, using custom controls, and changing the layout with shell extensions. Custom business types help reduce the code that you write. For example, the Money data type can treat numeric types as currency. This eliminates the requirement to apply formatting in the user interface.

What is the difference between LightSwitch and WebMatrix?

  • Both are tools for building applications, but the approach and target audience is very different:  “WebMatrix is HTML UI and LightSwitch is Silverlight UI”.
  • WebMatrix is a tool that includes a Web server (IIS Developer Express), a simple database (SQL Server Compact), and programming framework (ASP.NET). It is targeted at non- professional developers to make it easier to create new websites from scratch, or use Microsoft’s Web Application Gallery to customize popular ASP.NET and PHP open source community applications. In contrast, LightSwitch is targeted at professional developers and power users looking to create custom Line of Business (LOB) applications using data from multiple sources.

Create Your First LightSwitch Application

If you want to create your first application in lightswitch than here are the steps that will guide you.

Summary

LightSwitch will not be for every developer or for every business application you write, especially if you have sophisticated needs.  At the same time LightSwitch applications themselves are robust and are built on top of .NET technologies including Entities and WCF, the same technologies you already choose from when you write your apps today.

Useful Reference :


Hope this will help !!!

Jay Ganesh

Shout it

kick it on DotNetKicks.com