hi friends ...............
i need automatic id generation code .....there is a registration form.when ever a customer press the add button then immediately generation id (like 001) and store the details with id in database ..... i am using microsoft visual studio 2008 and sql database...
Loading
Satyapriya NayakPosted Feb 6, 2013, 1:39 AM
Thanks
Jignesh TrivediPosted Feb 5, 2013, 2:42 AM
hi,
you can use SCOPE_IDENTITY to find out id for inserted record.
SqlConnection con = new SqlConnection("your connectionstring");
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
// write your query instead of my department master query.
command.CommandText = "Insert into DepartmentMaster values('newName','new decription');select @id = SCOPE_IDENTITY()";
command.Connection = con;
con.Open();
command.Parameters.Add("@id", DbType.Int32).Direction = ParameterDirection.Output;
int res = command.ExecuteNonQuery();
var newValue = command.Parameters["@id"].Value;
in the variable new value you may find out next Available value you can direct prompt this value to user else process it with Appending first zero.
in my example DepartmentMaster has one column called DepartmentId is Auto generated column in database
hope this will help you.
Satyapriya NayakPosted Feb 5, 2013, 1:32 AM
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string str;
SqlCommand com;
int count;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
autogenerated();
}
}
void autogenerated()
{
SqlConnection con = new SqlConnection(strConnString);
str = "select count(*) from employee";
com = new SqlCommand(str, con);
con.Open();
count = Convert.ToInt16(com.ExecuteScalar()) + 1;
txt_empid.Text = "00" + count.ToString();
txt_empid.Enabled = false;
con.Close();
}
protected void btn_insert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
str = "insert into employee values('" + txt_empid.Text.Trim() + "','" + txt_empname.Text.Trim() + "'," + txt_sal.Text.Trim() + ")";
com = new SqlCommand(str, con);
com.ExecuteNonQuery();
con.Close();
Label4.Text = "Records successfully Inserted";
txt_empname.Text = "";
txt_sal.Text = "";
autogenerated();
}
}