如何将空字符串转换为int [英] how to convert empty string to int

查看:1893
本文介绍了如何将空字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有两个文本框。



如何将空字符串转换为int

我这样的代码。





textbox1.Text =;



int a = convert.ToInt32(textbox1.Text);

i得到错误



输入字符串的格式不正确。

int a = Convert.ToInt32(textbox1.Text) ;

解决方案

使用 Int32 .TryParse方法 [ ^ ]

  bool  success =  Int32 .TryParse(textbox1.Text, out  a); 



a将包含0,如果转换没有成功。


另一个解决方案就是检查你的文本框是否为空:



  if (textBox1.Text.Equals( ))
{
int a = 0 ;
}





稍后您必须使用正则表达式来检查输入框是否包含除数字之外的任何内容。如果它没有然后立即转换为整数,否则显示错误。


大家好,



< pre lang =cs> int ? lat1 = string .IsNullOrEmpty(txtempid.Text)? ( int ?) null :Convert.ToInt32(txtempid.Text);
int empid = Convert.ToInt32(lat1);





此代码正常工作


Hi all,

I have two textboxes.

how to convert empty string to int
my code like this.


textbox1.Text="";

int a= convert.ToInt32(textbox1.Text);
i got the error

Input string was not in a correct format.
int a = Convert.ToInt32(textbox1.Text);

解决方案

Use Int32.TryParse Method[^]

bool success = Int32.TryParse(textbox1.Text, out a);


a will contain 0, if the conversion was unsuccessful.


Another solution for this is to just have a check and see if your textbox is empty:

if(textBox1.Text.Equals(""))
{
    int a = 0;
}



Also later on you have to use regular expressions to check if the input box contains anything other than numbers. If it doesn''t then convert it to integer straight away, otherwise display an error.


hi all,

int? lat1 = string.IsNullOrEmpty(txtempid.Text) ? (int?)null : Convert.ToInt32(txtempid.Text);
          int empid = Convert.ToInt32(lat1);



this code working fine


这篇关于如何将空字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆