C# Variables and Data Types in WinForms

How to use and convert data in a UI context

In Windows Forms apps, you’re constantly working with user input and displayed values — and that means working with variables and data types. Whether it’s reading from a TextBox or showing a number in a Label, you’ll need to store, convert, and use data correctly.

Let’s revisit how variables work in C#, and how to use them in your forms.


🧰 What Are Variables?

Variables are named containers that hold data in your app.

string name = "Alice";
int age = 25;
bool isMember = true;

🔢 Common C# Data Types in UI

TypeExample ValueUsed For
string"Hello"TextBox input, Label text
int42Numeric input, counters
double3.14Prices, scores, floating-point
booltrue / falseCheckBox states, toggles
DateTimeDateTime.NowDate pickers, timestamps

🧱 Declaring and Using Variables

string userName = textBoxName.Text;
int quantity = 3;
bool accepted = checkBoxAgree.Checked;

✅ Notice how you can read data from UI controls and store it in variables.


🔄 Converting Data from TextBoxes

TextBoxes always return strings. To use numbers, you need to convert:

int age = int.Parse(textBoxAge.Text);
double price = double.Parse(textBoxPrice.Text);

💡 Use TryParse() for safe conversions:

int age;
if (int.TryParse(textBoxAge.Text, out age))
{
    MessageBox.Show("Your age is " + age);
}
else
{
    MessageBox.Show("Please enter a valid number!");
}

✅ This avoids crashes if the user types non-numeric text.


🔤 Strings in the UI

Strings are used everywhere in a WinForms app:

  • Showing output in a Label
  • Setting button text
  • Reading from input fields
labelGreeting.Text = "Welcome, " + textBoxName.Text + "!";

Or using string interpolation:

labelGreeting.Text = $"Welcome, {textBoxName.Text}!";

🎯 Example: Price Calculator

private void btnCalculate_Click(object sender, EventArgs e)
{
    double price;
    int quantity;

    if (double.TryParse(txtPrice.Text, out price) &&
        int.TryParse(txtQuantity.Text, out quantity))
    {
        double total = price * quantity;
        lblTotal.Text = $"Total: £{total}";
    }
    else
    {
        lblTotal.Text = "Invalid input!";
    }
}

✅ Uses double and int, stores input in variables, and outputs a string


🧪 Quick Challenge

🧩 Create a form with:

  • 2 TextBox controls: Price and Quantity
  • 1 Button to calculate total
  • 1 Label to display total

Add code that:

  • Reads values
  • Converts to numbers
  • Multiplies them
  • Displays result using a formatted string

📚 Summary

ConceptDescription
stringMost common type in UI controls
int, doubleUseful for numeric input & calculation
boolComes from checkboxes, toggles, states
.TextUsed to get/set string values on controls
TryParse()Safely convert strings to numbers

✅ Best Practices

  • ✅ Always check input before parsing (TryParse)
  • ✅ Use descriptive variable names (userName, totalPrice)
  • ✅ Keep logic short and readable in event handlers
  • ✅ Format strings nicely when displaying results

🎓 Want to Go Further?

  • Store user data in classes or structs
  • Use arrays or lists to track multiple items
  • Validate input using regex or helper methods
  • Convert data for saving to file or database

💬 Unsure how to handle mixed inputs or get numbers from a TextBox?
I can help troubleshoot your code or build a complete example!