Press "Enter" to skip to content

Lesson 12.1 – Add the remaining UI controls

Lesson Objectives

At the end of this lesson, you will know…

  • Some of the other controls you can add to a form

 

Now that we have the game world built, we can start connecting it up with the user interface, so the player can start moving around, battling monsters, and completing quests.

So, we’ll add the rest of the buttons, for the player to perform actions, and RichTextBoxes and DataGridViews, so we can display what is happening for the player.

 

Adding the remaining UI controls to the screen

In case the steps below aren’t clear, here’s a video of me adding the controls to the game’s form, and changing their properties.

 


Link to video on YouTube

 

Step 1: Start Visual Studio Express 2013 for Desktop, and open the solution.

 

Step 2: Right-click on the SuperAdventure.cs for, in the SuperAdventure project, then select “Open” or “View Designer”.

 

Step 3: Just like when you added the labels for “Hit Points” and “Gold”, you’re going to drag some controls on the form, and then change some of its properties.

Add one Label control

Use these values for it:

Label control
TextXY
Select action617531

Add two ComboBox controls

Use these values for them:

Combobox controls
NameXY
cboWeapons369559
cboPotions369593

 

Add six Button controls

Use these values for them:

Button controls
NameTextXY
btnUseWeaponUse620559
btnUsePotionUse620593
btnNorthNorth493433
btnEastEast573457
btnSouthSouth493487
btnWestWest412457

 

Add two RichTextBox controls

Use these values for them:

RichTextBox controls
NameXYWidthHeightReadOnly
rtbLocation34719360105TRUE
rtbMessages347130360286TRUE

 

Add two DataGridView controls – from the “Data” group of the Toolbox

When you add the DataGridViews, you’ll see a popup box with some options. Uncheck the boxes for “Enable Adding”, “Enable Editing”, and “Enable Deleting”.

Use these values for them:

DataGridView controls
NameXYWidthHeight
dgvInventory16130312309
dgvQuests16446312189

 

For both the DataGridViews, you also need to set these properties:

ReadOnly = True

EditMode = EditProgramatically

AllowUsersToAddRows = False

AllowUsersToDeleteRows = False

AllowUsersToResizeRows = False

Enabled = False

MultiSelect = False

RowHeadersVisible = False

 

Summary

We’ve added some new control types to the game.

The ComboBoxes will let the player select which weapon, or potion, they want to use during a battle. The RichTextBoxes will display status information about where the player is at and what is happening to them. And the DataGridViews will show lists of what the player has in their inventory and what quests they have.

 

Source code for this lesson

These is no source code for this lesson

 

Next lesson: Lesson 13.1 – Functions, procedures, and methods

Previous lesson: Lesson 11.1 – Using a static class

All lessons: Learn C# by Building a Simple RPG Index

38 Comments

  1. Sorthious
    Sorthious January 1, 2015

    Thanks for the lessons!! On this page the label ‘Select Action’ is listed as X-627, which is outside the form bounds. In the video you put it at 617…Anyway, ty again!

    • Scott Lilly
      Scott Lilly January 22, 2015

      Thanks. I’ve got that (and the other value) fixed, although it may take a while for the site to update with the new screenshots.

  2. Emma
    Emma March 12, 2016

    hi Scott,

    I’m kind of late to the game, but so far I’ve found this tutorial to be really great! I’ve actually followed up to lesson 16.3, and was getting ready to run the game. There are 5 errors in my SuperAdventure.Designer.cs class, and I can’t figure out how to fix them. I get a red squiggly line under rtbLocation_TextChanged in line 231 that looks like this:this.rtbMessages.TextChanged += new System.EventHandler(this.rtbMessages_TextChanged);

    this.rtbMessages.TextChanged += new System.EventHandler(this.rtbMessages_TextChanged);

    and I’m getting that sort of error with the same issue on lines 142, 151, 221, and 295 as well. I assume this is something I did wrong while creating the UI, as previous lessons haven’t altered this class.

    Any advice?

    thanks.

    • Scott Lilly
      Scott Lilly March 12, 2016

      Hi Emma,

      Try commenting out those lines with the red squiggles in SuperAdventure.Designer.cs (add two slashes “//” in front of them).

      What probably happened was that you accidentally double-clicked on some of the controls in the UI (like the Messages RichTextBox). When you do this, Visual Studio will create an eventhandler in the Designer page, and create a function in the .cs page that the eventhandler calls. But, if you overwrite the code in the .cs file with the the code in the lesson, that will eliminate the function. Then, the eventhandler in the Designer page will not be able to find its function, and this error happens. You can find out a bit more about this in Lesson 21.3 – Add a button and create its eventhandler in code, without the UI design screen

      Please let me know if commenting out those lines does not solve the problem.

  3. Raven6990
    Raven6990 November 23, 2016

    Been having some issues once I got down to Lessen 19 and was getting ready to do the xml for storing player data when I decided to go back through and fix any errors that may have happened. Most of them were simple things such as mistyped commands, however in superadventure.cs I am having 228 errors that I can not seem to find out how to fix. I managed to fix one error where for some reason the dgvInventory was not working, I found out that the properties didn’t save the name for the dgv, I was getting the dgvQuests as an error as well and went and changed the name under the properties for that one too, well that did not fix it, I am still getting that error for dgvQuests and I am also getting errors on every line after the dgvQuests are called.

     

    Here is a copy of my SuperAdventure.cs code

    http://pastebin.com/qAeF6b2R

    • Scott Lilly
      Scott Lilly November 25, 2016

      In the code on Pastebin, it looks like there are some lines missing at the end – probably closing curly braces. I don’t know if that is only something in Pastebin, or if that is also in your program. If those ending lines are missing in your source code, that would cause problems. Can you check that?

      If those lines are in your code, can you copy the error messages to a Pastebin file? That will help me discover the source of the error messages.

      • eammon msetfi
        eammon msetfi May 3, 2017

        Exccelent tutorial thanks a lot, I am having compliation error, once importing your code. first error im getting is in the cboPotions & cboWeapons, under the code this.cboPotions.SelectedIndexChanged += new System.EventHandler(this.cboPotions_SelectedIndexChanged); and the others are in the // Refresh player data in UI
        lblHitPoints.Text = _player.CurrentHitPoints.ToString();
        UpdateInventoryListInUI();
        UpdatePotionListInUI();

        • Scott Lilly
          Scott Lilly May 3, 2017

          Can you tell me what the error message says (the complete text)?

  4. Raven6990
    Raven6990 November 28, 2016

    Pretty sure I found the problem, got a bunch of empty labels on here from when I made the Hit points, Gold, and so on, I remember losing some of them and having to recreate them and I think that is causing problems im going to try and restart this whole thing now and see if that fixes the problem. Thank you for your reply

  5. Noah Limes
    Noah Limes December 10, 2016

    Hi, I don’t know if you recognize me from another question but thanks for that answer; it cleared up some of it and for the parts I still don’t understand, I’ll reply to in that question.

    My problem for this question is this: I saw in a different question that double-clicking controls creates an eventhandler, so I looked through my SuperAdventure.cs and saw some extra stuff that I assumed were from double-clicking…and I deleted them. I thought it was okay because they appeared to be random. label3_Click was followed by label8_Click.

    Long story short, errors started happening. They say I don’t have a definition for label3_Click, label8_Click, or dataGridView1_CellContentClick. I can’t open my form at risk of data loss.

    The stupidest thing I did was save and close because I had to do something and I already had other errors (which I believe I fixed now) so I couldn’t run it to check at the time.

    Is there a source code file somewhere of the SuperAdventure.cs code after lesson 12.1 so I can rewrite whatever I deleted?

    • Scott Lilly
      Scott Lilly December 10, 2016

      You might be able to fix the problem by cleaning up SuperAdventure.Designer.cs. That file probably has links to the deleted functions. If you comment out the lines that are trying to connect to the missing functions, that could fix the problem.

      There is more information on how eventhandlers work in Lesson 21.3. The lines pointing to the missing functions probably have squiggly lines under them (Visual Studio’s way to indicate a line with a problem).

      Please tell me if you try that, and it does not fix the problem. I don’t have a copy of the project after each lesson. But, we can figure out a way to get your program working again.

      • Noah Limes
        Noah Limes December 11, 2016

        I commented out the 3 errors. That reduced me down to 1 error. That error is in the Player class where I have the line “public List Inventory { get; set; }”. Under Inventory there are red squiggles and the description reads “Inconsistent accessibility: property type ‘List’ is less accessible than property ‘Player.Inventory’.

        Lesson learned so far: comment out; don’t delete

        • Noah Limes
          Noah Limes December 11, 2016
          namespace Engine
          {
              public class Player : LivingCreature //creates the "blueprint" for players to be created from. Also, it has a parent class called LivingCreature, with all of LivingCreature's variables
              {
              public List<InventoryItem> Inventory { get; set; }
              public List<PlayerQuest> Quests { get; set; }
              public int Gold {get; set;}
              public int ExperiencePoints {get; set;}
              public int Level{get;set;}//the get; set; name does what the names say. 
              public Player(int gold, int experiencePoints, int level, int maxiumHitPoints, int currentHitPoints) : base(maxiumHitPoints, currentHitPoints)
                  {
                      Gold = gold;
                      ExperiencePoints = experiencePoints;
                      Level = level;
                      Quests = new List<PlayerQuest>();
                      Inventory = new List<InventoryItem>();
                  }
              }
          }
          
          • Scott Lilly
            Scott Lilly December 11, 2016

            Check the Item and InventoryItem classes, to make sure they are public – that they start with “public class Item” and “public class InventoryItem”.

  6. Noah Limes
    Noah Limes December 11, 2016

    That was exactly what it was. It’s working now!

    Thanks for patiently answering my bombardment of questions. You’re awesome.

    • Scott Lilly
      Scott Lilly December 11, 2016

      You’re welcome. Now that you experienced that error, you’ll know what to look for the next time you see it. That is a large part of programming – knowing what to do when you encounter an error. 🙂

  7. Rickardo
    Rickardo January 7, 2017

    Why do we use DataGridViews instead of anyof the other options

    • Scott Lilly
      Scott Lilly January 7, 2017

      We’re using a DataGridView because we want to display rows and columns of data – like a spreadsheet. For the Inventory, we’ll display the names of the items, and the quantity of the item that the player has. For the Quests, we’ll display the name of the quest and if the player has compelted it (or not).

      DataGridView controls let us add (and remove) rows, and we can fill the columns with properties of the objects we add to the datagrid.

  8. Eric
    Eric May 12, 2017

    public SuperAdventure()
    {
    InitializeComponent();
    _player = new Player(10, 10, 20, 0, 1);
    MoveTo(World.LocationByID(World.LOCATION_ID_HOME));
    _player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_RUSTY_SWORD), 1));

    lblHitPoints.Text = _player.CurrentHitPoints.ToString();
    lblGold.Text = _player.Gold.ToString();
    lblExperience.Text = _player.ExperiencePoints.ToString();
    lblLevel.Text = _player.Level.ToString();
    }

    When I run the program, “MoveTo(World.LocationByID(World.LOCATION_ID_HOME));” crashed and showed “An unhandled exception of type ‘System.TypeInitializationException’ occurred in SuperAdventure.exe

    Additional information: The type initializer for ‘Engine.World’ threw an exception.” and I found out that the error was from Word.PopulateLocation. I am wondering if you have seen this problem?

    • Scott Lilly
      Scott Lilly May 12, 2017

      I’ve seen this error before. It happens if there is an error in the constructor-like function for a static class (or one of the functions it calls).

      You can probably find the exact location of the error by using the technique in this video: https://www.youtube.com/edit?o=U&video_id=Ide5v6Cfk6o. If you try that, and cannot find the source of the error, can you please upload your solution (including its sub-folders, and all the files in them) to GitHub, or Dropbox, so I can investigate?

  9. Justin
    Justin October 25, 2017

    Love your tutorial man keep up the good work. Quick and hopefully simple question: How do I change the color of text?

    Like say I wanted to change the damage received from enemies to red, how could I do that? I’ve tried looking and couldn’t really find the answer I was looking for.

    Thanks in advance!

    • Scott Lilly
      Scott Lilly October 26, 2017

      Thanks Justin,

      Formatting text in a RichTextBox isn’t very obvious, and it usually involves some extra steps. But, here’s a way to change the color for part of the message you’ll display in a richtextbox: https://stackoverflow.com/questions/1926264/color-different-parts-of-a-richtextbox-string.

      I believe there are some changes to the messages in future lessons. So, you might want to add this after you complete everything else. You’ll probably need a second function to display the damage message – so you only change the color for the damage, and not all messages.

      If you have problems adding this in, let me know.

  10. Jeremy Hartley
    Jeremy Hartley May 24, 2018

    Hi Scott,
    I have once again started going through your tutorials after stepping away for almost two years. 🙂 I was the one who mentioned that I am totally blind, and I am using screen reading software to complete these tutorials. In fact, you modified your lessons which really help out for use with a screen reader. The tables listing all of the properties for each of the controls are perfect! 🙂

    I just wanted to provide a bit of an FYI as it relates to the two combo box controls. Both the cboWeapons and cboPotions combo boxes were added to the form with no associated label controls. I have just finished Lesson 12.1, so these missing labels may be added programmatically later. But, just in case the labels are never added for these two controls, I will provide a tip to make controls with no labels more accessible to screen reading software.

    Currently, when the program is run without labels for each of the weapons and potions combo boxes, the screen reader simply announces “combo box” if the control is focused using the Tab key. Of course, this isn’t very helpful! 🙂 However, if you go into the properties for any one of the combo box controls, you will see two properties (AccessibleDescription, and AccessibleName). The one we are concerned with is AccessibleName. If, for example, you provide a value of “weapons” as the value of the AccessibleName property, the screen reading software will announce “weapons combo box” when the control receives focus. Well, it technically announces “weapons edit combo box”, but that is due to the “style” property being currently set to “drop-down”.

    Just thought your readers would be interested in this little bit of info. As I go through these lessons, I could provide more of these screen reader tips if you wish. It is a great exercise for me, taking a mainstream project like this, and making sure it is “accessible” for screen reader users. 🙂

    • Scott Lilly
      Scott Lilly May 25, 2018

      Hi Jeremy,

      It’s great to hear from you again. I’ll keep a note of your suggestions and create a new lesson on how to modify the program to make it accessible for the player.

    • Brian
      Brian April 6, 2019

      your blind and programming? that is simply incredible.

  11. Joshua Sims
    Joshua Sims May 23, 2019

    HI Scott,

    Sorry to bug you so much, I am having a problem where the buttons are not rendering when I hit start. There are no build errors.

    Do you know what may be up?

    Thanks

    • Scott Lilly
      Scott Lilly May 23, 2019

      There are a few things that might cause that. I’d need to look at the code to figure out exactly where the problem is. Can you upload your solution to Dropbox or GitHub?

  12. Patrick
    Patrick February 18, 2020

    Hi Scott,
    I’m really enjoying the course so far, it has really helped me learn some of the key concepts that other tutorials just haven’t been able to hit for me. Could you explain your though process in putting all of the world data in to one large class instead of keeping the separate pieces in their own classes and then calling them in the World method to be built together? The way you have it put together makes it pretty hard to read and remember what each of the parameter values is supposed to setting.
    Thanks!

    • Scott Lilly
      Scott Lilly February 19, 2020

      Hi Patrick,

      The main reason I put all the world data in one class is because they need to be populated in a certain order. We need to have the items created before we can create monsters – because monsters have an inventory full of items. We need to have items, monsters, and quests before we create locations, because locations have quests and monsters (which need items).

      If you look at the lessons 04.1 through 07.2 of the WPF version of this class (https://www.scottlilly.com/build-a-cwpf-rpg/), you’ll see a different way to handle creating world data. If you look at lessons 14.1 through 14.5 of that course, you’ll see how we move all that data to external XML files – making the factory classes even smaller.

      Let me know if you look at those lessons and have any questions.

  13. TJ
    TJ June 22, 2020

    Hi! Sorry to bother you with something so simple, but DataGridView doesn’t appear to be there? The data tab as a whole isn’t there and I can’t figure out why. Do you have any suggestions?

    • Scott Lilly
      Scott Lilly June 23, 2020

      Can you upload your solution (including the directories under it, and all the files in those directories) to GitHub or Dropbox, so I can look at it?

      • Sarien
        Sarien July 13, 2020

        Hi Scott!

        Thank you so much for this tutorial – it’s been AWESOME so far!

        I just wanted to add to TJ’s comment – it looks like the most recent version of Visual Studio no longer has DataGridView available in the toolbox. It seems some other people have had the same issue:

        https://www.reddit.com/r/VisualStudio/comments/f66dlx/cant_add_datagriddatagridview_in_a_windows_form/

        And here are some instructions on how to bypass it, however, this may be a little difficult for a beginner…

        https://gunnarpeipman.com/datagridview-dotnet-core-31/

        Any other workarounds or a different way to make this information appear for the player?

        Thank you!

        • Scott Lilly
          Scott Lilly July 13, 2020

          You’re welcome!

          This sounds like the SuperAdventure project might be in .NET Core, and not .NET Framework. That’s the cause of about half the problems I see.

          If the DataGridView isn’t showing up for you, can you right-click on the SuperAdventure project, select “Properties”, select the “Application” tab, and tell me what version of .NET the project is using? That will let me know if that is the problem, or if there is something else that needs to be done.

          Thanks,
          Scott

          • Sarien
            Sarien July 13, 2020

            Hi Scott!

            I just checked and it says: .Net Core 3.1.

            However, the Engine Assembly says .Net Standard 2.0.

            I hope that helps.

            Thank you so much for your time!

          • Scott Lilly
            Scott Lilly July 13, 2020

            That might cause a problem in some of the other lessons. If you get stuck, you may need to make them .NET Framework projects. Unfortunately, there isn’t a simple, automated way to convert the projects.

            Let me know if you get stuck and need help later on.

  14. John
    John October 4, 2022

    I have a problem where when I try and select a potion or weapon it shows nothing in the drop down, and if I select a box and then try to attack the game crashes and tells me that the cboWeapons was empty.

    System.NullReferenceException: ‘Object reference not set to an instance of an object.’

    currentWeapon was null.

Leave a Reply

Your email address will not be published. Required fields are marked *