Click here to Skip to main content
15,908,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
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
C#
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?

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)[^]
 
Share this answer
 
v2
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.
 
Share this answer
 
C#
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);
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900