错误显示如下输入字符串格式不正确 [英] error shows as follows input string was not in a correct format
问题描述
我正在验证用户是否输入了textbox1,学生ID是否在数据库中。
该代码如下;
i am validating whether the user enters in the textbox1 student id is there in the database or not.
for that code as follows;
SCon.Con.Open();
string str = "Select count(*) from Studdet where studid = '" + txt_Studid.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(str, SCon.Con);
int a = Convert.ToInt16(str);
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
Label4.Text = "Correct Student id";
return;
}
else
{
Label4.Text = "InCorrect student id is there";
return;
}
SCon.Con.Close();
在运行模式下,当我在textbox1中输入学生ID并单击按钮时显示如下错误;
输入字符串格式不正确
什么是我上面的代码中的问题请帮帮我。
问候,
Narasiman P.
in the run mode when i enters the student id in the textbox1 and click the button shows error as follows;
input string was not in a correct format
what is the problem in my above code please help me.
Regards,
Narasiman P.
推荐答案
删除单引号
Remove that Single Quote
SCon.Con.Open();
string str = "Select count(*) from Studdet where studid = " + txt_Studid.Text.ToString() ;
SqlCommand cmd = new SqlCommand(str, SCon.Con);
int a = Convert.ToInt16(str);
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
Label4.Text = "Correct Student id";
return;
}
else
{
Label4.Text = "InCorrect student id is there";
return;
}
SCon.Con.Close();
你好
如果你调试你的项目你在这一行找到错误
Hello
If you debug your project you find error on this line
int a = Convert.ToInt16(str);
因为str有
because str have "
Select count(*) from Studdet where studid
永远不会转换为int
请删除此行并执行此操作你收到的结果
..
"
which is never convert to int
please remove this line and execute this you get result
..
SCon.Con.Open();
string str = "Select count(*) from Studdet where studid = '" + txt_Studid.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(str, SCon.Con);
int a = Convert.ToInt16(str);
int count = (int)cmd.ExecuteScalar();
SCon.Con.Close();
if (count > 0)
{
Label4.Text = "Correct Student id";
return;
}
else
{
Label4.Text = "InCorrect student id is there";
return;
}
</pre>
thanks
and also closed connection before return because it will un-reachable code.
if problem persist please give me your reviews.,...
之前将字符串转换为int,确保字符串不为null ...
像这样使用
Before converting the string to int, make sure that the string is not null...
use like this
int i = String.IsNullOrEmpty(str) ? -1 : Convert.ToInt16(str);
这篇关于错误显示如下输入字符串格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!