Click here to Skip to main content
15,895,779 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my given Stored procedure
C#
Create PROCEDURE GetSalary(@Id int,@Sal money output )
AS
BEGIN
     SELECT @Sal=EmpSalary from Emp 
	where EmpId =@Id
	
END


program.cs
C#
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();
        }
Posted
Updated 17-Jun-14 23:41pm
v2
Comments
Kornfeld Eliyahu Peter 18-Jun-14 5:44am    
What value txtId.Text has?
ArunRajendra 18-Jun-14 6:00am    
Verify proper values are entered in txtId. Validate the input before you pass it on to sql.

1 solution

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.
C#
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;
    ...
Then use the checked-and-fine id value in your parameters

I would suggest though, that you use AddWithValue instead:
C#
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Id", id);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900