dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online MembersShine S
Phagu Mahato
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » Code Snippets » ASP.NET WebForms

How to get last inserted ID from ASP.NET Code behind?


Posted Date:     Category: ASP.NET WebForms    
Author: Member Level: Diamond    Points: 20


In this article I am going to explain about how to get last inserted id or name or no etc. from database in code behind. This code sample is help you in future to get insertion id.



 


Description :


In many cases we are like to get last inserted id from database instead of pass query again to get last inserted id, using OUTPUT keyword we can get in the single query. Refer below code sample I have explained in detailed.

Client side


I placed three textboxes to collect employee no, name, salary.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to get last inserted ID</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="600" cellpadding="0" cellspacing="0" align="center">
<tr>
<td height="40" colspan="2">
<b>Get Last Inserted ID</b>
</td>
</tr>
<tr>
<td height="40" colspan="2">
<b><asp:Label ID="lblResult" runat="server"></asp:Label></b>
</td>
</tr>
<tr>
<td height="30">
Enter Employee number
</td>
<td height="30">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30">
Enter Employee name
</td>
<td height="30">
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="30">
Enter Employee salary
</td>
<td height="30">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td height="40" align="center" colspan="2">
<asp:Button ID="btnInsert" runat="server" Text="Insert and Get ID"
onclick="btnInsert_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Server side



using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblResult.Text = "";
}
protected void btnInsert_Click(object sender, EventArgs e)
{
string query = "";
//I have returned here auto genearated ID if you want return employee number then use OUTPUT INSERTED.eno in below query
query = "insert into emp(eno,empname,sal) OUTPUT INSERTED.ID values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')";
lblResult.Text= "Last Insert Auto Generated ID is" + RetID(query);
}

//Retrieve last inserted id from database using below method
public int RetID(string query)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
sqlcmd = new SqlCommand(query, sqlcon);
try
{
sqlcon.Open();
int newId = 0;
newId = Convert.ToInt32(sqlcmd.ExecuteScalar());
return newId;
}
catch (SqlException ex)
{
return 0;
}
finally
{
sqlcon.Close();
sqlcon.Dispose();
}
}
}

Output :


Image

Source code:


Client Side: ASP.NET
Code Behind: C#

Conclusion

I hope this code snippet is help you to know about get last inserted id through same query.

Attachments
  • Inserted_ID_source (43966-74236-Inserted-ID-source.rar)





  • Did you like this resource? Share it with your friends and show your love!


    Responses to "How to get last inserted ID from ASP.NET Code behind?"

    No responses found. Be the first to respond...

    Feedbacks      

    Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: How to UnZip files in ASP.NET?
    Previous Resource: How to read XML data based on condition and display in gridview?
    Return to Resources
    Post New Resource
    Category: ASP.NET WebForms


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Inserted ID  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.