Question
I have a C# text box value, TextBoxD1.Text, and need to convert its text to an int before storing the value in a database. What is the safe way to perform this conversion and handle invalid input?
Short Answer
You will learn how to turn text entered in a C# TextBox into an integer, choose between int.Parse, int.TryParse, and Convert.ToInt32, validate user input, and pass the resulting number safely to a database command.
Concept
A TextBox always exposes its contents through the Text property as a string, even when a user typed only digits. An int is a numeric type that stores whole numbers, such as 42 or -7.
Before using text as a number, C# must parse the string: it examines the characters and creates an integer value if the text represents a valid whole number.
For values entered by users, int.TryParse is usually the best choice. User input can be blank, contain spaces, include letters, or be larger than an int. TryParse reports whether conversion worked without throwing an exception, so your program can show a useful validation message instead of failing.
This matters especially before database work. Validate and convert the value first, then send the integer through a typed SQL parameter. This keeps invalid data out of the database and avoids building SQL by concatenating text.
Mental Model
Think of a TextBox as a note someone hands you. Every note is paper, so every value starts as text—even a note that says 25.
Parsing is like checking whether that note contains a valid whole-number address:
"25"can become the number25."twenty-five"cannot become anint.""has no number to convert.
int.TryParse is a safe checker: it tells you whether the note is acceptable and gives you the number only when it is.
Syntax and Examples
The recommended syntax for user-entered text is:
if (int.TryParse(TextBoxD1.Text, out int value))
{
// value is a valid int here.
}
else
{
// The text was not a valid int.
}
Example in a button-click handler:
private void saveButton_Click(object sender, EventArgs e)
{
if (!int.TryParse(TextBoxD1.Text, out int quantity))
{
MessageBox.Show("Enter a valid whole number.");
return;
}
MessageBox.Show($"Quantity to save: {quantity}");
}
TryParse returns true when conversion succeeds. The converted number is stored in quantity. If it returns false, the return stops the save operation before invalid data is used.
If invalid input is impossible because the value comes from a trusted source, int.Parse is shorter:
int quantity = int.Parse("42");
However, int.Parse throws a FormatException for text such as "abc", so it is normally not the right default for a user-editable text box.
Step by Step Execution
Consider this code:
string input = " 125 ";
if (int.TryParse(input, out int orderId))
{
Console.WriteLine(orderId);
}
else
{
Console.WriteLine("Invalid order ID");
}
Execution steps:
inputholds the string" 125 ".int.TryParsechecks whether the string represents a whole number. Leading and trailing whitespace is allowed.- The text is valid, so
TryParsereturnstrue. - The parsed integer
125is assigned toorderId. - The
ifblock runs and prints125.
Now change the input:
string input = "125 items";
TryParse returns false because extra non-numeric text is present. The else block runs, and no unsafe conversion occurs.
Real World Use Cases
Converting text to integers is common whenever users or external systems provide numeric data as strings:
- Order forms: Convert a quantity text box into an integer before calculating totals.
- Search screens: Convert an entered customer ID into an integer before querying records.
- Configuration files: Parse values such as
"30"for a retry limit or timeout count. - CSV imports: Convert columns such as product stock or employee IDs from text to numbers.
- Web APIs: Validate an ID received as a string before looking up database data.
- Desktop applications: Read a selected year, age, or number of copies from a form control.
Real Codebase Usage
In real applications, parsing is typically combined with validation and an early return:
if (!int.TryParse(TextBoxD1.Text, out int productId) || productId <= 0)
{
MessageBox.Show("Product ID must be a positive whole number.");
return;
}
// Continue only with a valid productId.
The early return keeps the successful path less nested and prevents database code from running with bad input.
When saving or querying a database, use a parameter rather than inserting textbox text into SQL:
using var command = new SqlCommand(
"INSERT INTO Products (Quantity) VALUES (@quantity)",
connection);
command.Parameters.Add("@quantity", System.Data.SqlDbType.Int).Value = quantity;
command.ExecuteNonQuery();
A typed parameter communicates that quantity is an integer, handles formatting correctly, and avoids SQL injection risks caused by concatenating user input into a query.
For applications with several validation rules, developers often place parsing and validation in a dedicated method, view model, or service instead of putting all logic directly in a button handler.
Common Mistakes
Using int.Parse directly on user input
int value = int.Parse(TextBoxD1.Text);
This throws an exception when the text is blank, contains letters, or exceeds the int range. Prefer TryParse for editable input.
Ignoring the result of TryParse
int.TryParse(TextBoxD1.Text, out int value);
Save(value);
If parsing fails, value becomes 0. You may accidentally save 0 unless you check the returned bool.
if (!int.TryParse(TextBoxD1.Text, out int value))
{
return;
}
Save(value);
Treating 0 as automatically invalid
Zero is a valid int. Whether it is allowed depends on your business rule. For example, quantity may need to be greater than zero, while a discount percentage may allow zero.
Building SQL with string concatenation
string sql = "INSERT INTO Products (Quantity) VALUES (" + TextBoxD1.Text + ")";
This mixes validation, formatting, and SQL construction. Parse first and use a parameter instead.
Using int for values outside its range
An int ranges from -2,147,483,648 to 2,147,483,647. Use long.TryParse when the domain can contain larger whole numbers, such as some external identifiers.
Comparisons
| Approach | On valid input | On invalid input | Best use |
|---|---|---|---|
int.TryParse(text, out int value) | Returns true and assigns value | Returns false; no exception | User input and unreliable text |
int.Parse(text) | Returns an int | Throws an exception | Trusted text that must be valid |
Convert.ToInt32(text) | Returns an int | Throws for invalid numeric text; null becomes 0 | General conversions when null behavior is intended |
long.TryParse(text, out long value) | Returns a long | Returns false; no exception | Whole numbers outside the int range |
TryParse validates the format. Add separate rules to validate the meaning:
if (!int.TryParse(TextBoxD1.Text, out int age) || age < 0 || age > 130)
{
MessageBox.Show("Enter an age from 0 to 130.");
}
Here, "999" is a valid integer format but an invalid age according to the application rule.
Cheat Sheet
// Safest default for a TextBox
if (int.TryParse(TextBoxD1.Text, out int value))
{
// Use value
}
else
{
// Show validation feedback
}
// Require a positive value
if (!int.TryParse(TextBoxD1.Text, out int value) || value <= 0)
{
MessageBox.Show("Enter a positive whole number.");
return;
}
// Parse trusted text only
int value = int.Parse("42");
Rules to remember:
TextBox.Textis always astring.- Prefer
int.TryParsefor user input. - Always check
TryParse'strueorfalseresult. intaccepts whole numbers, not decimal values such as"4.5".- Whitespace around a number is accepted by
TryParse. - Check application rules such as minimum and maximum values after parsing.
- Use SQL parameters to save parsed values to a database.
FAQ
How do I convert a TextBox value to an integer in C#?
Use int.TryParse(TextBoxD1.Text, out int value). Check whether it returns true before using value.
Why does int.Parse crash on my text box input?
It throws an exception if the input is empty, contains non-numeric characters, includes a decimal value, or is outside the int range.
Does int.TryParse accept spaces around a number?
Yes. For example, " 42 " parses successfully as 42.
What happens when int.TryParse fails?
It returns false. The output variable receives 0, so do not use that variable unless you checked the return value.
Can I convert decimal text such as "12.5" to an int?
Not directly with int.TryParse, because int stores whole numbers. Use decimal.TryParse or double.TryParse if fractional values are allowed, then define a deliberate rounding rule if an integer is eventually required.
How should I save the converted integer to SQL Server?
Parse and validate it first, then add it as a typed SQL parameter, such as command.Parameters.Add("@quantity", SqlDbType.Int).Value = quantity;.
Should I use Convert.ToInt32 instead of int.TryParse?
For text typed by a user, TryParse is usually better because it handles invalid input without exceptions. Convert.ToInt32(null) also returns 0, which can hide missing input.
Mini Project
Description
Build a small C# form-save routine that reads a product quantity from a text box. The routine rejects missing, non-numeric, and non-positive quantities before it would save the value. This mirrors validation commonly performed before database inserts or updates.
Goal
Validate a text box value and produce a safe positive integer that is ready to send to a database parameter.
Requirements
Use int.TryParse to convert the text box value.
Reject input that is not a whole number.
Reject zero and negative quantities.
Display a clear message when validation fails.
Use the validated integer in a parameterized SQL command.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Access Modifiers and static: public, private, protected, and Defaults
Learn how C# public, private, protected, and default access control visibility, and how static differs from instance members.