Saturday, May 10, 2014

Use of Stored Procedure and Execute Scalar in C# using ADO.NET



Design the form like this:



write code on form load:
       SqlConnection con = new SqlConnection(@"Data Source=HIMANSHU-PC;Initial                                            Catalog=Emp;Integrated Security=True");
       SqlCommand cmd;
       SqlDataReader dr;


1. Write code for select the data by empid using Stored Procedure.

            con.Open();
            cmd = new SqlCommand("MyPro", con);
            cmd.Parameters.AddWithValue("@id", textBox1.Text);
            cmd.CommandType = CommandType.StoredProcedure;
            dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                textBox2.Text = dr[1].ToString();
                textBox3.Text = dr[2].ToString();
                textBox4.Text = dr[3].ToString();
            }
          con.Close();


2.  Code to use Execute Scalar:

            con.Open();
            cmd = new SqlCommand("SELECT Max(Salary) from Emp", con);
            object sum_sal = cmd.ExecuteScalar();
            MessageBox.Show("Sum of Salary=" + sum_sal);
            con.Close();

No comments:

Post a Comment