Monday, 15 April 2013

How to use ExecuteScalar in Ado.Net with C#


How to use ExecuteScalar  in Ado.Net  with  C#

create database test
use test
create table McaStudent(RollNo int identity(1,1),StudentId as 'Mca' + cast(RollNo asvarchar(10)),Name nvarchar(50),Gender nvarchar(50),Course nvarchar(50),Addressnvarchar(max))


insert into McaStudent values('Somesh', 'Male','B. Tech.','Kanpur')

*************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         con = new SqlConnection("Data Source=kush;Initial Catalog=test;Integrated Security=True");
    }      
    SqlConnection con;
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        con.Open();

       // SqlCommand cmd = new SqlCommand("insert into McaStudent (Name,Gender,Course,Address) output inserted.StudentId values ('" + txtName.Text + "','" + RbGender.SelectedValue + "','" + ddlCourse.SelectedItem.Text + "','" + txtAddress.Text + "')", con);
        SqlCommand cmd = new SqlCommand("insert into McaStudent  output inserted.StudentId values ('" + txtName.Text + "','" + RbGender.SelectedValue + "','" + ddlCourse.SelectedItem.Text + "','" + txtAddress.Text + "')", con);
       LStudentId.Text= ""+cmd.ExecuteScalar();
       con.Close();
       LMessage.Text = "Add Success fully";
 }



    protected void BtnNoRow_Click(object sender, EventArgs e)
    {
       int count=0;
      String sqlQuery = "Select COUNT(*) from McaStudent";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        try
        {
            con.Open();
            //Since count  is intger,System.Object, a typecast is must
            count = (Int32)cmd.ExecuteScalar();
            LMessage.Text = count.ToString();

        }
        catch (Exception ex)
        {
            LMessage.Text = ex.Message;
        }
        finally
        {
            con.Close();
        }
     
    }
}


2 comments:

  1. Excellent Post. Also visit http://www.msnetframework.com/

    ReplyDelete
  2. this artical more helpfull for us..

    ReplyDelete