Create a random selection app for Windows Phone
This article shows how to create a UI for adding user-entered items to ListBox and then randomly selecting a "winner". This might be useful, for example, for choosing the winner of a raffle. The example also shows how to use the (third party) InputPrompt to get user input, how to remove items from the ListBox, and how to select a random number.
See Also
Article Metadata
Code Example
Tested with
Compatibility
Article
Contents |
Introduction
The "Raffling" application is shown below. The user enters items by pressing the + button, and can remove items by selecting them from the list. When all items are entered the Start Raffle button can be pressed to randomly select one of the items.
The following sections show how each part of the application are constructed.
Implementation overview
The main screen of the application is shown below. In addition to the normal Silverlight application infrastructure like page and application title, we have two buttons for adding items and starting the random selection, a ListBox for displaying the items.
Items are added using the InputPrompt from the Coding4Fun Tools (which is easier to use than creating your own "popup" user input component.)
The random item is selected using the C# Random object.
Create The Project
- Create an empty Windows Phone Project.
- Launch Visual Studio -> click on File->New Project.
- Select Windows Phone Application (Visual C# Template).
- Add Name and Location of the project, then click OK to create the project.
Using Coding4Fun tools
In this application we are going to use a very cool third party component to get user inputs called: InputPrompt. You can download it here at : Coding4Fun.Phone.Toolkit and save and extract it on any location you want. There is more information on this component here: InputPrompt in depth
- Now we need to add "Coding4Fun.Phone.Controls.dll assembly" as Reference to our Project for us to be able to use it.
- On the Solution Explorer Right Click on References > Add Reference > Browse > and locate Coding4Fun.Phone.Controls.dll inside the extracted folder
- Then Add this Using Statement above using Coding4Fun.Phone.Controls;
- And you are now ready to use the InputPrompt component
Building and Designing the UI
On your MainPage.xaml You may refer to the illustration above.
- Draw the Button for triggering the Raffle event. Design and name it whatever you want (I named it: btnRaffle).
- Draw also a Button for Adding Items to be raffled. Design and Name it whatever you want (I named it: btnAddItem).
- (Last) Draw a ListBox for the added items to be stored. Design and Name it whatever you want (I named it: listItems).
Now that our UI ingredients are done, we can now start putting some action on them.
Adding Actions to our UIs
Next, we'll learn how to add items to the ListBox programatically.
On your MainPage.xaml Double Click on the Add Item Button to add an EventHandler and MainPage.cs will be opened it should look something like this below
// btnAddItem Click Event Handler
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
}
Getting user input using the InputPrompt component
When the user clicks the Add Item button, we want our app to give them a place to input their desired items. This is where the InputPrompt component is useful.
Now add the following code snippet inside the function block (I'll explain every line of code in the comment lines)
// create an instance of the InputPrompt Object
InputPrompt input = new InputPrompt();
// add the completed event handler
input.Completed += new EventHandler<PopUpEventArgs<string, PopUpResult>>(input_Completed);
// set the title of the InputPrompt
input.Title = "Add an Item";
// set the message of the InputPrompt
input.Message = "Name, Product, Number, Object, anything....";
// define the input scope NameValue as Text (for general)
input.InputScope = new InputScope { Names = { new InputScopeName() { NameValue = InputScopeNameValue.Text} } };
// show the InputPrompt
input.Show();
Adding items to the ListBox
When you write the above code, it will give you an error something like "Error : The name 'input_Completed' does not exist in the current context" This is because we don't have any input_Completed handler for our InputPrompt yet. So we'll create it right now.
Paste this anywhere (make sure it's inside your class's scope).
// InputPrompt Completed / Add Item Event Handler
void input_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
{
// check if the user inputted atleast 1 character
if (e.Result.Length > 0)
{
// add the inputted item
listItems.Items.Add(e.Result);
}
else // if not, tell the user
{
MessageBox.Show(Please enter an item with atleast 1 character.");
}
}
Removing Items in the ListBox
Go to your MainPage.xaml and click your ListBox, and on the Properties Section, go to Events > and look for the "Tap" Event, then double click it to generate the Handler code. It should look something like this:
// ListItems Tap Event Handler
private void listItems_Tap(object sender, GestureEventArgs e)
{
}
Paste the following code inside the block
// get the MessageBoxResult: if they clicked "Ok" then execute, if they clicked "Cancel" do nothing
if (MessageBox.Show("Remove " + listItems.SelectedItem + "?", "Remove", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
// Remove the selected item
listItems.Items.Remove(listItems.SelectedItem);
}
Now if we run it, we are already able to remove items.
Getting the random item in the ListBox
This is where we'll learn how to get a random item in the list.
On your MainPage.xaml double click on your Raffle / Raffling Button. The code should look something like this:
// btnRaffle Click Event Handler
private void btnRaffle_Click(object sender, RoutedEventArgs e)
{
}
- Now, we need to show to the user the randomly chosen item right? Okay, Fine, Copy the below code, paste it, and run
// if there are atleast 2 items on the list
if (listItems.Items.Count > 1)
{
// create a Random object Instance
Random random = new Random();
// generate a random number from 0 up to the size of the list ( we did this because we don't want to get an index that is not on the list)
int randomNumber = random.Next(0, listItems.Items.Count);
// set the selected item by index corresponding to the generated random number
listItems.SelectedIndex = randomNumber;
// show the chosen/selected item (you can say"the winner is / or anything you want")
MessageBox.Show("The chosen item is " + listItems.SelectedItem.ToString());
}
else // if there are no items / only 1 item in the list tell the user to add atleast two items
{
MessageBox.Show("You have no items to raffle \n\n Tap the + to add an item);
}
Summary
Feel free to copy this application, tweak it, expand it, improve it, share it with the whole world.




Hamishwillee - Minor subedit
Hi Oliver
Thanks for your article. I've given it a minor subedit - thanks for mostly using the correct wiki styles! I like how you've shown the images to help make it clear what it does.
I guess my first thought was "what is a raffler" and "what does this have to do with my friends buying me foods?". I think that what this app does is randomly select a user entered item from a list of items - for me it would be more useful if the name made this clear. You could then explain what this has to do with a raffle - ie raffle is one use case for a random selector UI.
In terms of structure and introduction, I think it helps to make it very clear up front what people can learn from the article (which you have done to some extent). So its worth saying this
I'd also consider adding sub headings for the sections which highlight the above sections.
Typically wiki articles are quite "dry". A conversational style is fine for blogs, but we tend to limit the humorous asides in wiki articles so that people can get to the information faster, which is what this is all about!
Thanks again, I think some people will find this useful.
Regards
Hamishhamishwillee 09:59, 21 August 2012 (EEST)
Nemoryoliver - a BIG thank you.
Thank you very much for the suggestions again @Hamishwillee also for the minor edits.
I will clean this article and add those as what you've said. I am very thankful you are helping me.nemoryoliver 10:13, 21 August 2012 (EEST)
Hamishwillee - You're welcome
OK, so I have subedited this further for readability and structure. Please check out the changes to confirm that it still does what you want, and that you understand why the changes have been made (I can explain if this is not obvious)
You will note that I've removed some of the conversational style and your details from the end. The best place for your contact details is in your profile, which is linked in the articlemetadata up the top right of wiki pages. Can you please add it there, and make your profile public (in the preferences).
I have also moved the article - this is done using the menu under the "eye" symbol at the top right of the wiki page.hamishwillee 03:32, 22 August 2012 (EEST)