Display identity number on textbox or label
I used identity keyword in sql to genrate srno. on my from. but it genrated no. in sql table. i want to display these no. on my form when i save my entry. it should display in textbox or label. pls tell me the ans.
Prabhu RajaPosted Jan 3, 2012, 7:22 AM
You can Use Scope_Identity() function to retrieve identity column value .
//SQL Connections
String ConnectionString = ConfigurationSettings.AppSettings["DataSourceName"];
SqlConnection conn = new SqlConnection(ConnectionString);
String CommandString = "Insert Into CourseTable(CourseName, ShortName) Values (@CourseName, @ShortName);Select CourseID from CourseTable Where CourseID = SCOPE_IDENTITY()";
SqlCommand commandS = new SqlCommand(CommandString);
try
{
commandS.Parameters.Add("@CourseName", this.txtCourse.Text.Trim ());
commandS.Parameters.Add("@ShortName", this.txtShortName.Text.Trim());
conn.Open();
commandS .Connection = con;
SqlDataReader reader = commandS .ExecuteReader();
while(reader.Read())
{
// You can Get you auto generated number as
string getID = reader[0].ToString();
}
}
catch (Exception e)
{
}
finally
{
commandS.Parameters.Clear();
commandS.Dispose();
commandS =null;
conn.Close();
}
If this post helps you, then mark as "Correct Answer". Thank You
Krishna GaradPosted Jan 3, 2012, 6:00 AM
Create Stored Procedure Sp_Name
(
@Val1 DataType,
@val2 DataType,
@no DataType out
)
AS
Begin
Insert Into Table Values(@val1,@val2)
Set @no='Identity Is :'+CONVERT(Varchar(20),@@IDENTITY
End
This will display the identity after insert. If you want to display the identity value before insert then try
Select Max(IdentityCloumn+1)From TableName
And display this value in you lable or textbox.
Vijay YadavPosted Jan 3, 2012, 5:22 AM
When you save the data into the dastabase that time you can retrieve that data(i.e auto-generated number) in the textbox or label as per your convinient.