如何解决错误输入字符串不是正确的格式 [英] How Do I Resolve The Error Input String Not In Correct Format

查看:56
本文介绍了如何解决错误输入字符串不是正确的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给定的存储过程

Create PROCEDURE GetSalary(@Id int,@Sal money output )
AS
BEGIN
     SELECT @Sal=EmpSalary from Emp 
	where EmpId =@Id
	
END





program.cs



program.cs

SqlConnection con = new SqlConnection(Helper.ConnectionString);
             SqlCommand cmd = new SqlCommand();
             cmd.Connection = con;
             cmd.CommandText = "GetSalary";
             cmd.CommandType = CommandType.StoredProcedure;
             SqlParameter parId, parSalary;
             parId = new SqlParameter("@Id", SqlDbType.Int);
             parSalary = new SqlParameter("@Sal", SqlDbType.Money);
             parSalary.Direction = ParameterDirection.Output;
             cmd.Parameters.Add(parId);
             cmd.Parameters.Add(parSalary);
             parId.Value = int.Parse(txtId.Text);
             con.Open();
             cmd.ExecuteNonQuery();
             con.Close();
             if (parSalary.Value == DBNull.Value)
                 txtSalary.Text = "";
             else
                 txtSalary.Text = parSalary.Value.ToString();
        }

推荐答案

使用int.TryParse而不是int.Parse来处理用户输入,并尽早检查所有字段这样你就不会浪费精力去处理那些不会发生的事情。

Use int.TryParse instead of int.Parse to process user input, and check all fields as early as possible so you don't waste effort with things that aren't going to happen.
int id;
public void myMethod()
    {
    if (!int.TryParse(txtId.Text, out id))
       {
       // report input error to user
       return;
       }
    SqlConnection con = new SqlConnection(Helper.ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    ...

然后在参数中使用经过检查并且罚款 id 的值



我建议你改为使用AddWithValue:

Then use the checked-and-fine id value in your parameters

I would suggest though, that you use AddWithValue instead:

cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", id);


这篇关于如何解决错误输入字符串不是正确的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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