.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ADO.NET >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Saving the data to backend by self id

Posted By:Nikhil Kumar       Posted Date: February 27, 2010    Points: 10    Category: ADO.NET    URL: http://www.dotnetspark.com  

Saving the data to backend by self id. Get the last record id from database and increment in front end using C# code.
 

//Storing the data to backend


 protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data source = SAI; Initial Catalog = Datamaster; Integrated Security = true";
       

        try
        {
            //create  a sql command to get a unique contactID.

            SqlCommand cmd = new SqlCommand("Select MAX(cemployeeCode) from employee", con);
            // Open the database connection
            con.Open();

            //Execuete the sql command 
            int intNextID = (int)cmd.ExecuteScalar() + 1;

            //Create a command to add a new row...

            SqlCommand cmd1 = new SqlCommand(String.Format("Insert into employee (cemployeeCode,Name,Age) values({0},'{1}','{2}')", intNextID, TextBox1.Text, TextBox2.Text), con);

            //Execute the command 
            if (cmd1.ExecuteNonQuery() > 0)
            {
                Label1.Text = "Record Added";
                TextBox1.Text = "";
                TextBox2.Text = "";
            }
            else
            {
                Label1.Text = "Couldn't add record";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = "Error:" + ex.Message;
        }
        finally
        {
            //close the con.
            con.Close();
        }
    }
}

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend