Use PromptBox to get simple user input in Silverlight

When we create Silverlight application we will run into a situation where we need to get very simple input from a user apart from traditional ok or cancel. If you are after the simple ok or cancel then message box serve the purpose but if you need to get some kind of data from the user as simple as a number or a string, then we do not need to create popup window or child window in Silverlight if you are using component one controls.

Out of the box, component provides a user control called C1PromptBox which as the name suggests, prompt the user for an input and goes on it merry way without cluttering code with complicated code.

Let’s look at this with simple example;

C1PromptBox.Show(“Enter your age”, “Age prompt”, (s, r) =>
{
If (r ==MessageBoxResult.OK)
{
//age will be in s, parse the age out
}
else
{
// user pressed cancel
}
}

If you expect the last two line to execute after getting user input, then if condition has to be inside the C1PromoptBox.Show bot outside like the code shown

above. The proper way to write the code

In the above example, when the code executes it will prompt the small message box to enter the age and you parse or handle the value on the event user press ok button.

One thing we need to be mindful, the Show event is a delegate so if you have any instructions that need to execute after prompt is successful, it has to be inside the MessageBoxResult.OK condition not outside the show delegate since UI will take control back after show event is successful.

Here is a scenario;

  1. public void PromptAge()
  2. {
  3. int age = 0;
  4. C1PromptBox.Show(… get age);
  5. if (age <= 30)
  6. HandleLessThanThirtyAge();
  7. }
 

In the above example we are expecting the dialog to be shown for user to enter the age. After the user enters the age, line 05 gets control and executes HandlesLessThanThirtyAge method if the age is less than or equal to 30. But that is not how it works. When PromptAge executes, it execute prompt box and while it wait for user to enter something, the UI thread continues and executes 05 through so age will be always 0 and it never executes the method on 06. The reason for that is, the behavior on how to handle ok or cancel is delegate inside the prompt box. So for it work properly. ie, after user enters the ages, get the age and based on the age to execute the HandleLessThanThirtyAge, we need to move the if condition inside the PromptBox delegate itself as shown below

  1. public void PromptAge()
  2. {
  3. C1PromptBox.Show("msg", "prompt", (s, r) =>
  4. {
  5. if (r == MessageBoxResult.OK)
  6. {
  7. //parse age from s
  8. if (age <= 30)
  9. HandleLessThanThirtyAge()
  10. }
  11. };
  12. }
One of the feature missing in this is default value for the prompt, I requested this feature with Component One and it is schedule be part of their feature release. By providing most commonly used value as default value, we could save one key stoke for the user. Once the feature is available I will update this blog.
Advertisements

Creating Excel like grid in Silverlight – C1FlexGridBook

If you are developing a business application, you will run into a situation where the end users want to export the data to excel and do some work there and then import the sheet back to the application. This is very normal, the main reason the users ask for it because Silverlight does not have a grid which look and behaves like Excel. There are bunch of work around for this, but I really like the C1FlexGridBook control from Component One. This gird out of the box gives excel like look and feel with less amount of code. Some of the basic features like created tabbed sheet at the bottom of the control to look like worksheets in Excel and many more.

Lets see how to create a simple excel like grid using C1FlexGridBook. What we need to create is Component One dlls for

 image

We need Excel, FlexGridBook and FlexGridBook.

So how do we go about adding the control. So in the XAML I created simple tag for C1FlexGridBook as follows

image

I am planning to create the columns in the code behind (I am trying figure out a problem so two birds with single stone). The data that I am binding is a collection of customers like the following

image

where the data structure is

image

When the page is navigated to the pages I create a customer collection like the following

image

Now all is left is to create the sheets and bind the data to the grid in each sheet. Here is where you have to be very careful. I would strongly recommend you to create skeleton sheets but do not creating individual grid with data binding, rather, you create the grid for the first and default sheet or the sheet the user wants to see. So here are the steps

Create the sheets with AddSheet and pass in the sheet name as the first parameter as shown below.

image

We also bound out collection to grid by doing that, the current grid associated with the sheet get the data from customers. We set the autogenerate to false since I have collection that I want to appear properly. So below create the dynamic columns on the fly

image

now the question is why would I need a cell template? Since the data is boolean I want to display a check box rather than textblock.

image

That’s it. Now if you would run the code you will see a result something like the following,

image

With very little code from control perspective, we got a grid which looks like excel. If you notice, it has following excel features out of the box

1. Row and Column numberings.

2. Office theme.

3. Fixed column heading for application.

4. Default Excel like filtering.

5. At the bottom, you see the sheets and also it comes with default behavior to let the user create new sheets.

6. Excel like navigation to move between sheets with forward and backward navigation button.

7. Navigate to first or last sheet with fast navigation.

8. If you have lot of sheets and want to navigate to a specific sheet, then right lick on the left or right navigation, it shows available sheets and just click on the sheet name you navigate to that sheet.

I really enjoyed working with this control. If you like it or would like to know more about this control send me a note.

Making Grid editable through program for C1FlexGrid

In some scenarios, you may have some user options, when they were selected, you want to take the user to a specific row and make it editable rather than asking the user to double click to enter editing. It is very easy to do it in Component One using following two lines

_flex2.Selection = new C1.Silverlight.FlexGrid.CellRange(0, 0);
_flex2.StartEditing(true);

First like set the row and cell where you want the control to go to and the second line enable editing for you.

If you still have trouble getting focus change the code to

Dispatcher.BeginInvoke(() => { this._flex2.Focus(); });.

Elegant way to create combo box in C1FlexGrid (Tip 8)

You are asked to create a Silverlight application to show a grid where one or more columns are combo boxes. This is a very common scenario. It can be very easily solved by creating a data edit template on the grid column and show a combo box, with a converter. There are lots of examples for this scenario, one in code project and another one in Manish blog. When I binged, there are lot of information in stack overflow. There is a much better solution if you are using Component One.

If you have component one, then we can remove all these data template, combo box and converters with simple property called Value Converter. Lets see the problem statement. We need to create a grid, with employee name and job title.

image

When you enter title in edit mode, it show available jobs like the following

image

Nothing special here, it is the standard combo box which shows all the available jobs for user to pick from. So how do we solve this problem using the special Value Converter?

Lets start from ViewModel this time. 

Code Snippet
  1.  
  2. public List<Person> People
  3. {
  4.     get
  5.     {
  6.         List<Person> list = new List<Person>();
  7.         list.Add(new Person { ID = 1, Name = "Ajay", JobID = 1 });
  8.         list.Add(new Person { ID = 2, Name = "Jeeem", JobID = 2 });
  9.         return list;
  10.     }
  11. }

Nothing new in the view model, it is same as you would build a collection in any other program. How about View?

Code Snippet
  1. <c1:C1FlexGrid Name="_flex" ItemsSource="{Binding People}" AutoGenerateColumns="False">
  2.     <c1:C1FlexGrid.Columns>
  3.         <c1:Column Binding="{Binding Name}"/>
  4.         <c1:Column Binding="{Binding JobID, Mode=TwoWay}" Header="Title"/>
  5.     </c1:C1FlexGrid.Columns>
  6. </c1:C1FlexGrid>

Look at that, there is nothing special here either. We have a grid with two columns, first column is name and second column is Job ID. Please note that, we are not using combo box here. Ok so far we did not do anything new and I still want a combo box in second column. Lets go to the view code behind, that’s where the magic happens.

Code Snippet
  1. public Dictionary<int, string> dict = new Dictionary<int, string>();
  2.  
  3. public MainPage()
  4. {
  5.     InitializeComponent();
  6.     dict.Add(1, "Manager");
  7.     dict.Add(2, "Team Lead");
  8.     _flex.Columns[1].ValueConverter = new ColumnValueConverter(dict);
  9. }

We first create a dictionary, where we are going to keep the options available to show in the combo box. Line 6 and 7 adds two job titles to the dictionary and finally in line 8, we say, for second column use the value converter and point to new instance Column Value Converter with dictionary collection. This informs flex grid that, this column needs to a combo box and use the dictionary to show the string value of the value bound to the column.

Look at the code, it is very simple and elegant. I really like the approach more than writing data template, converters etc.,

One things, I haven’t figured out yet is to bind the value converter directly to view model property. If we could do it, we can eliminate all code from code behind. If I find a solution, I will post it here.

Component One Silvelright FlexGrid Tip 7 (ChildItemsPath with heterogeneous collection)

In one of my previous blog I have explained how to create tree view inside the grid using ChildItemsPath. There was a limitation at that time (prior to version 206), the child item must be of the same type of parent collection. In another words, both parent and child should be of same type. The best example is Person class. In a person class you can have children, but the children have to of type Person itself. In a way it was kind of limiting. With drop 206, Component One removed the limitation and now you can have children of different type. To show how it is done, lets look at the two classes that I am going to use today.

public class SalesPerson
    {
        public string Name { get; set; }
        public List<Sales> Children { get; set; }
    }
    public class Sales
    {
        public string Name { get; set; }
        public int Quantities { get; set; }
        public int Amount { get; set; }
    }

So we have two classes one is sales person and another one is sales. Each sales person have made number of sales and that I want to display in grid using ChildItemPath. Lets look at the XAML

<c1:C1FlexGrid ItemsSource="{Binding SalesPeople}" ChildItemsPath="Children" AutoGenerateColumns="False">
            <c1:C1FlexGrid.Columns>
                <c1:Column Binding="{Binding Name}"/>
                <c1:Column Binding="{Binding Quantities}"/>
                <c1:Column Binding="{Binding Amount}"/>
            </c1:C1FlexGrid.Columns>
        </c1:C1FlexGrid>

Nothing new here, everything is same as before. In the previous version of FlexGrid, when you run, you will get run time error, but with new drop 206, you will not get any error and the result should be something like

image

There you go, it is as simple as that.

Component One Silvelright FlexGrid Tip 6 (Group Header customatization)

Continuing our previous example of using Data Table to create grid on the fly, we will add one more column for grouping purpose to produce an output like the following

image

This also shows how to do grouping when using DataTable in Silverlight. So lets look at the code which generates the data to populate the grid and also grouping.

private void LoadData()
{
   _dataTableWithData = new DataTable();
   _dataTableWithData.Columns.Add("ID");
   _dataTableWithData.Columns.Add("Name");
   _dataTableWithData.Columns.Add("Age");
   _dataTableWithData.Columns.Add("Group");
   for (int i = 0; i < 10; i++)
   {
      int grp = ((i>3)?1:i);
      _dataTableWithData.Rows.Add(i, "Name" + i.ToString(), i, grp);
   }
   var gd = _dataTableWithData.DefaultView.GroupDescriptions;
   gd.Add(new PropertyGroupDescription("Group"));
}

As you can see, we create group row as we would create normal group row in FlexGrid. When we run the code it creates the groups properly but I do not like the default group header information in the group row. It shows

Group: value (number item)

What if I do not want to show the number of item in the parenthesis, how would I go about not showing it? That is what we are going to see today. This is easily achieved by using a custom converter for GroupHeaderConverter. Here is the custom header converter that we need to do to show only ‘Group : GroupName’

public class GroupHeaderConverter:IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
     var group = value as CollectionViewGroup;
     if (group != null)
        return string.Format("Group: {0}", group.Name);
     return null;
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
   throw new NotImplementedException();
  }
}

As you can see it is very simple value converter. For every group, we check and see if the row is a group row and if it is, then just return “Group: ” + group.name. One thing you need to make sure to use, the first type conversion. Make sure you you get the group information of type CollectionViewGroup. With that you get all group related information. Which is very powerful if you want to handle grouping completely different. Now that we have a group header converter, we need to let flex grid know to use this converter for the group headers by

_flex.GroupHeaderConverter = new GroupHeaderConverter();
That's all about it, now if you run the program you get the group header the way we wanted it to be.

image


Not only we saw how to customize the group header, we also saw how to do grouping in Data Table. Thanks Bernardo for the pointers.

Working with DataTable in Silverlight 4

Silverlight 4 out of the box does not support DataTable as its desktop counter part, WPF. But third party controls are here for the rescue. In this blog we will look at, what it take to create a simple grid and use Data Table that we love. As you might have guessed it, I am using Component One controls. Component One provides a namespace C1.Silverlight.Data, which have DataTable implementation that we have been using. So now that we know, we can use Data table, lets create a simple Grid and populate the data.

Create a Silverlight application and add grid control in your XAML as follow;

<Grid x:Name="LayoutRoot" Background="White">
        <c1:C1FlexGrid ItemsSource="{Binding DataTableWithData, Mode=TwoWay}" IsReadOnly="False" AutoGenerateColumns="True" Name="_flex"/>
    </Grid>

Nothing new here, my Flex Grid control bound a property in my view model. Before we go and code, we require following references in our project to run

c1.silvelright.dll

c1.Silvelright.data

System.Windows.Data

System.Windows.Controls.Data

Now lets look at the view model code;

private DataTable _dataTableWithData;

publicDataView DataTableWithData

{

     get

   
{

        if(_dataTableWithData == null)

            LoadData();

        return_dataTableWithData.DefaultView;

     }

}

_dataTableWithData property is our underlying data source. Which is nothing but DataTable, which is Component One data table type. If you notice we are not really binding data table to the grid control rather, we are binding DataView to the grid control. DataView implements the IEnumerable interface thus make it bindable to grid control. If you were like me trying out and not seeing the data in your grid, probabily your property type is incorrect.

Now lets look at the code which loads data to the data table

private void LoadData()
{
     _dataTableWithData = new DataTable();
     _dataTableWithData.Columns.Add("ID");
     _dataTableWithData.Columns.Add("Name");
     _dataTableWithData.Columns.Add("Age");
     for (int i = 0; i < 10; i++)
     {
          _dataTableWithData.Rows.Add(i.ToString(), "Name" + i.ToString(), i);
     }
}

There is nothing special here, creating and populating the data table as you would do in any other format. Now lets run and see the result;

image

 

That’s about it. To summarize

1. Make sure you use the references I mentioned above in your project.

2. Use Data Table as local variable to hold data but do not bind control to that property.

3. Use DataView type for binding it to the grid.

4. To bind data table to grid, you return ‘DefaultView’ of the data table.