Below here is my code to Retrieve Auto Increment ID After Inserting data into database.
However, I am getting Auto Increment ID before Inserting data into database.
How can I get auto increment ID after insert into database?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RetrievePRReqID();
}
}
//Retrieve ID method
private void RetrievePRReqID()
{
try
{
string query = "Select IDENT_CURRENT('tblPRRequest')";
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand cmd = new SqlCommand(query, sqlCon);
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
int value = int.Parse(reader[0].ToString()) ;
txt_PRNO.Text = value.ToString();
}
}
catch(Exception)
{
throw;
}
finally
{
if(con.State == ConnectionState.Open)
{
con.Close();
}
}
}
//Request button Method
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
}
By referring sample answer from #Mx.Wolf, I modified a bit to get the right answer, below here is the codes that is working :
protected void btn_Request(object sender, EventArgs e)
{
object id ;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.PRReqID " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
As stated in SQL Server documentation
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-ver15
The OUTPUT clause may be useful to retrieve the value of identity or computed columns after an INSERT or UPDATE operation.
You have to change your SQL statement
INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName)
OUTPUT inserted.ID
-------^^^^^^^^_^^
VALUES (#RequestTo,#RequestFrom,#RequestedByName)
and now you can use ExecuteScalar to get the inserted value
protected void btn_Request(object sender, EventArgs e)
{
int id= 0;
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"output inserted.ID" +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
id = (int)sqlcmd.ExecuteScalar(); //the result is of Object type, cast it safely
}
}
Debug.WriteLine(id.ToString()); // Access it like this
}
Try this:
protected void btn_Request(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO tblPRRequest (RequestTo,RequestFrom,RequestedByName) " +
"VALUES (#RequestTo,#RequestFrom,#RequestedByName)";
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
using (SqlCommand sqlcmd = new SqlCommand(insertCmd, conn))
{
sqlcmd.Parameters.Clear();
SqlCommand sqlCmd = new SqlCommand(insertCmd, sqlCon);
sqlcmd.Parameters.AddWithValue("#RequestTo", lblPurchasingDept.Text);
sqlcmd.Parameters.AddWithValue("#RequestFrom", ddlDept.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#RequestedByName", SUserName.Text);
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Direction = ParameterDirection.Output;
sqlcmd.ExecuteNonQuery();
}
}
***//After Insert into the table, I want to retrieve latest generated Auto Increment ID in here.***
sqlcmd.Parameters["#ID"].value; // Access it like this
}
In case you can chage the ExecuteNonQuery to ExecuteScalar, then it would be even easier: What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?
Related
I am making a basic web form with basic fields like name, email, number.
I just want, when i enter the number, rest of the fields are populated in the other textboxes based on that number from sql server.
Any help would be appreciated.
Code is as follows :
string ConnectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
string cmd = "IF NOT EXISTS(Select * from tbl_registration where Email = #Email OR MobileNo = #MobileNo) insert into tbl_registration values(#FirstName, #LastName,#Email,#MobileNo,#Address_1,#Address_2,#City,#State)";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using(SqlCommand com = new SqlCommand(cmd, con))
{
com.Parameters.AddWithValue("#FirstName", txtfname.Text.Trim());
com.Parameters.AddWithValue("#LastName", txtlname.Text);
com.Parameters.AddWithValue("#Email", txtemail.Text);
com.Parameters.AddWithValue("#MobileNo", txtmob_no.Text);
com.Parameters.AddWithValue("#Address_1", txtaddress1.Text);
com.Parameters.AddWithValue("#Address_2", txtaddress2.Text);
com.Parameters.AddWithValue("#City", txtcity.Text);
com.Parameters.AddWithValue("#State", txtstate.Text);
con.Open();
int success = com.ExecuteNonQuery();
if (success > 0)
{
Response.Write("<script>alert('Registration successfull')</script>");
}
else
{
Response.Write("<script>alert('Registration Not Sucessfull')</script>");
}
}
}
}
You should write the method definition as shown below on the text box changed event.
This is not the complete query answer. Here is a reference for you.
using (SqlConnection conn = new SqlConnection(CSs))
{
string query = "Your SQL Query here";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "sometablename");
firstnametext.Text = Convert.ToString(ds.Tables["sometablename"].Rows[0]["Firstname"]);
}
Here you need to properly handle the null for the data table.
I have a databse where the user can track new models coming into shop but they only keep one of each model, I'm not sure how to stop the user from repeating the same model. I've seen some previous answers on this site but I'm getting errors when using the code in my own.
private void check_Click(object sender, EventArgs e)
{
string query = "INSERT INTO tbl_phones(model) VALUES(#model)";
using (SqlConnection sqlconn = new SqlConnection(#""))
using (SqlCommand comm = new SqlCommand(query, sqlconn))
{
sqlconn.Open();
comm.Parameters.Add("#model, SqlDbType.NVarChar).Value = phoneinput.Text;
comm.ExecuteNonQuery();
This should work (get a count of phones where model is entered, if is less than one then insert).
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(#model)";
string checkQuery = "SELECT COUNT(*) FROM tbl_phones WHERE model = #model";
using (SqlConnection sqlconn = new SqlConnection(#""))
{
sqlconn.Open();
SqlCommand checkCommand = new SqlCommand(checkQuery, sqlconn);
checkCommand.Parameters.AddWithValue("#model", phoneinput.Text);
if((int)checkCommand.ExecuteScalar() < 1)
{
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("#model", phoneinput.Text);
insertCommand.ExecuteNonQuery();
}
}
}
Edit - if you decide to set model to be a primary key, you can catch the exception like so -
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(#model)";
using (SqlConnection sqlconn = new SqlConnection(connectionString))
{
sqlconn.Open();
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("#model", "test");
try
{
insertCommand.ExecuteNonQuery();
}
catch(SqlException ex)
{
if (ex.Number == 2627)
{
// Phone already exists, do some stuff
}
else throw;
}
}
}
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
How to add data into Specified columns in mysql database table using c# button click, once i clicked the button it will be passing to the catch
here is my add button code
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES ("
+ this.depIDInput.Text + ",'"
+ this.depnameInput.Text + "','"
+ this.dep_branchIDInput.Text + "')";
//This is command class which will handle the query and connection object.
MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();// Here our query will be executed and data saved into the database.
conn.Close();
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
here is all the columns of the table,
INSERT INTO `bcasdb`.`tbl_student`
(`reg_id`,
`std_fname`,
`std_lname`,
`tbl_batch_batch_id`,
`gender`,
`dob`,
`email`,
`mobile`,
`contact_address`,
`home_address`,
`status`,
`course_id`,
`depart_id`,
`parent_name`,
`telephone`,
`nationality`,
`nic`,
`passport_no`,
`acadamic_qulification`,
`current_employement`,
`gce_ol`,
`gce_al`,
`birth_certifiacte`,
`copy_of_nic`,
`police_clerence`,
`tbl_studentcol`)
VALUES
I believe your code should be rewritten as following:
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = #"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES (#depId, #depName, #branchId)";
//This is command class which will handle the query and connection object.
using (MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(Query, conn))
{
cmd.Parameters.Add("#depId", this.depIDInput.Text);
cmd.Parameters.Add("#dep_name", this.depnameInput.Text);
cmd.Parameters.Add("#branchId", this.dep_branchIDInput.Text);
cmd.ExecuteNonQuery();
}
}
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
Currently I am executing two queries against two different tables and getting this exception,
The connection was not closed. The connection's current state is open.
This is what I am trying to do,
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
connection.Open();
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I am doing this because Table2 has userID as foreign key and must be deleted before deleting user actually
you are calling Open() twice. You can remove the second call Open().
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
// connection.Open(); // remove this line
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
The second connection.Open() is not required as it will be open from first statement.
Still to be on the safer side, you can use
if (connection.State == ConnectionState.Closed)
connection.Open();
The second connection.Open(); doesn't need to be there. The first one is enough; as the error message says, it's already open.
One connection can perform multiple queries, with only a single call to Open.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(deleteStatement, connection))
{
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd2 = new SqlCommand(deleteStatement2, connection))
{
cmd2.Parameters.Add(new SqlParameter("#userID", userID));
int result2 = cmd2.ExecuteNonQuery();
if (result2 == 1)
{
BindData();
}
}
}
}
I think this will work:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
string deleteStatement = "Delete from Table1 where userID=#userID";
string deleteStatement2 = "Delete from Table2 where userID=#userID";
using (SqlConnection connection = new SqlConnection(CS()))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = deleteStatement;
cmd.Parameters.Add(new SqlParameter("#userID", userID));
cmd.ExecuteNonQuery();
cmd.CommandText = deleteStatement2;
int result = cmd.ExecuteNonQuery();
if (result == 1) BindData();
}
}