我有一個表格,我希望用戶輸入他們的名字、姓氏和年齡
但在此之前,我希望用戶不能將文本框留空 我的問題是獲取年齡,我的資料必須是 int 型別,但我不知道年齡文本框是如何為空的給用戶一個錯誤。
string firstName = tbxName.Text;
string lastName = tbxFamily.Text;
int age = Convert.ToInt32(tbxAge.Text);
if (string.IsNullOrEmpty(tbxName.Text))
{
MessageBox.Show("???? ??? ?????? ??? ?? ???? ????");
}else if (string.IsNullOrEmpty(tbxFamily.Text))
{
MessageBox.Show("???? ??? ???????? ??? ?? ???? ????");
}else if (!string.IsNullOrEmpty(tbxAge.Text))
{
MessageBox.Show("???? ?? ??? ?? ????? ????");
}else
{
MessageBox.Show(" ??? ?????? " firstName " ??? ???????? " lastName " ?? ?? " age " ?? ?????? ??? ?? ");
}
uj5u.com熱心網友回復:
試試下面的代碼
string firstName = textBox1.Text;
string lastName = textBox2.Text;
int age;
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("???? ??? ?????? ??? ?? ???? ????");
}
else if (string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("???? ??? ???????? ??? ?? ???? ????");
}
else if (string.IsNullOrEmpty(textBox3.Text))
{
MessageBox.Show("???? ?? ??? ?? ????? ????");
}
else if (!string.IsNullOrEmpty(textBox3.Text))
{
if (textBox3.Text.All(char.IsDigit))
{
age = Convert.ToInt32(textBox3.Text);
}
else
{
MessageBox.Show("???? ?? ??? ?? ????? ????");
}
}
else
{
MessageBox.Show(" ??? ?????? " firstName " ??? ???????? " lastName " ?? ?? " age " ?? ?????? ??? ?? ");
}
uj5u.com熱心網友回復:
要回答標題問題(假設“int 型別文本框”只是一個TextBox):
int num = string.IsNullOrWhiteSpace(textBox1.Text) ? -1 : Convert.ToInt32(textBox1);
這使用三元運算子“?”
小心 Convert.ToInt32 如果它不能轉換會拋出例外。使用 int.TryParse() 代替
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537449.html
標籤:C#窗体整数
上一篇:從另一個專案添加外部檔案夾
