Click here to Skip to main content
14,361,624 members
Rate this:
Please Sign up or sign in to vote.
See more:
cmd.CommandText = "SELECT COUNT(Teacher_id) from Teacher";
               int newid = (int)cmd.ExecuteScalar();
               Label8.Text = "your Teacher_id is  "+Convert.ToString(newid);


//and also tried for
cmd.CommandText = "SELECT MAX(Teacher_id) from Teacher";
               int newid = (int)cmd.ExecuteScalar();
               Label8.Text = "your Teacher_id is  "+Convert.ToString(newid);
Posted
Comments
Ankur\m/ 4-Mar-14 0:45am
   
1st query is certainly going to give you the number of rows in the table. It is doing what it is supposed to do.
I am wondering what's wrong with your second query. It should give you what you want. Are you not getting the correct answer?
Rate this:
Please Sign up or sign in to vote.

Solution 4

Check out the following example:
string newid = "";

string sql = "INSERT INTO teachers (name, gender) VALUES (@name, @gender);" +
                    " SELECT SCOPE_IDENTITY();";

using (var con = new SqlConnection("your connection string") )
using (var cmd = new SqlCommand(sql, con)
{
    cmd.Parameters.Add("@name", SqlDbType.VarChar, 100).Value = txtName.Text;
    cmd.Parameters.Add("@gender", SqlDbType.VarChar, 20).Value = txtGender.Text;

    con.Open();
    newid = cmd.ExecuteScalar().ToString();
}

Read more: SCOPE_IDENTITY (Transact-SQL)[^]
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

If ur coloumn teacher column is identity than after insert query u have to concate one more query as given below...

Insert into tbl_teacher_mst values(); select cast(scope_identity() as bigint);

you have to execute both query as given sequence using execute scaler method of command class and it will return newely inserted identity value.
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

use ExecuteNonQuery in second Query

cmd.CommandText = "SELECT MAX(Teacher_id) from Teacher";
               int newid = (int)cmd.ExecuteNonQuery();
               Label8.Text = "your Teacher_id is  "+Convert.ToString(newid);
   
v2
Comments
ErBhati 4-Mar-14 7:11am
   
plz select as answer for others if it helps you....

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100