how do i get id of the last inserted row - c#

i want to display booking id of the last inserted row.my insert code is given below. pls anyone can give me code to display the id
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd;
SqlDataReader dr;
con.Open();
cmd = new SqlCommand("insert into [booking] values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "')", con);
cmd.ExecuteNonQuery();
}
}

I would suggest using something like this:
protected void Button1_Click(object sender, EventArgs e)
{
var cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using (var con = new SqlConnection(cs))
{
con.Open();
var cmd = new SqlCommand(
"DECLARE #IDReturnTable TABLE( ID INT ); INSERT INTO [booking] OUTPUT INSERTED.NameOfYourIdColumn INTO #IDReturnTable VALUES(#param1, #param2, #param3); SELECT ID FROM #IDReturnTable",
con);
cmd.Parameters.Add("#param1", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#param2", SqlDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add("#param3", SqlDbType.VarChar).Value = TextBox3.Text;
var returnedId = cmd.ExecuteScalar();
}
}
I didn't use all 11 Text Boxes, just 3 to illustrate the technique.

You will be better off doing this as a stored procedure, and less susceptible to injection.
To achieve it with your current code, add a call to ;SELECT SCOPE_IDENTITY():
cmd = new SqlCommand("insert into [booking] values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "');SELECT SCOPE_IDENTITY()", con);
And execute as scalar:
var id = cmd.ExecuteScalar();
(This assumes you have an identity column on your table)
To do it as a stored procedure:
If you have a finite number of values, you can just create the stored procedure normally, with an #Parameter for each TextBox.Text but with SELECT SCOPE_IDENTITY() at the end.
But it looks like you have a variable number of inputs, so see How to insert a multiple rows in SQL using stored procedures? which outlines an approach using a table paramater and one using a UDF to split a list of values.
Again, you would need to SELECT SCOPE_IDENTITY() at the end of the proc to pick up the identity of the last row.
For a detailed discussion on the ways of selecting the last inserted id see What is the difference between Scope_Identity(), Identity(), ##Identity, and Ident_Current?

Related

using comboboxes and textbox for date of birth

I combined 2 text boxes and text box. Don't know how to convert the string to datetime.
string DOb = $"{comboMM.SelectedValue}, {ComboDD.SelectedValue}, {txtYear.Text"";
string Query = "Insert into dbo.membertable(Given_Names, Last_Name, passport_No, Ctry_Origin, gender, M_status, DOb,MarAnn, Phone_No,Email,branch,Unit,H_address,city,states,Country,famdfrd_Name,famfrd_Number,famfrd_rship) Values('" + txtnames.Text + "','" + txtFamilyname.Text + "','" + txtPassport.Text + "','" + txtCountry.Text + "','" + ComboGender.SelectedItem + "','" + ComboMStatus.SelectedItem + "','" + DateB.Value.ToShortDateString() + "','" + MarAnn + "','" + txtPhoneNo.Text + "','" + txtEmailAdd.Text + "','" + ComboBranch.SelectedItem + "','" + ComboUnit.SelectedItem + "','" + txtAddress.Text + "','" + txtCity.Text + "','" + ComboState.SelectedItem + "','" + ComboCountry.SelectedItem + "','" + txtrelative.Text + "','" + TxtRphone.Text + "','" + txtRelationship.Text + "');";
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["PottersDB"];
String connectionString = conSettings.ConnectionString;
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(Query, con);
dr = cmd.ExecuteReader();
MessageBox.Show("Member Successfully Added");
Reset_Page();
con.Close();
}
As suggested in the comments, using Parameters in your query will simplify your code.
Please see the below code for an example. I have added a few extra comments to suggest improvements to your supplied code.
// Create a DateTime object from your controls, instead of a string representation.
var year = int.Parse(txtYear.Text);
var month = int.Parse(comboMM.SelectedValue);
var day = int.Parse(ComboDD.SelectedValue);
var dateOfBirth = new DateTime(year, month, day);
// Use parameters in your query instead of appending the string values
var query = "Insert into dbo.membertable(Given_Names, Last_Name, DOb, OtherFields) Values(#GivenNames, #LastName, #DOB, #OtherParameters);";
// Wrap your SqlConnection and SqlCommand in using blocks to ensure they are disposed correctly.
var connString = ConfigurationManager.ConnectionStrings["PottersDB"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#GivenNames", txtnames.Text);
cmd.Parameters.AddWithValue("#LastName", txtFamilyname.Text);
cmd.Parameters.AddWithValue("#DOB", dateOfBirth);
// As the query is just inserting, there's no need to create a data reader.
cmd.ExecuteNonQuery();
}
}
Also as mentioned by Avrohom Yisroel, a DatePicker control seems more suited to your application. It allows the user to select a date, which you can access from the SelectedDate property of the object. This would save you creating a TextBox for the year and two ComboBoxes for the day/month.
The simple answer is to use a date picker instead. That's what they are there for, it's what the user expects, it validates the input for you, it gives you a DateTime instead of a string you have to covert...
There's more, but that should be plenty!

C# Update in ado.net

Old records are not deleting. Update acts like insert.
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand("update studetail set name='" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "' where studentno='" + textBox1.Text + "'");
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
update acts like insert.
That's obvious cause you made it like so. Your below UPDATE statement is syntactically wrong
update studetail set name='" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section
It rather should be
update studetail set name='" + textBox2.Text + "',' gender = " + gen + "','" ...
Finally, you should consider using parameterized queries instead of concatanating user input likewise you are doing. It's prone to SQL Injection
SqlCommand cmd = new SqlCommand("update studetail set name= #name, gender = #gender, clas = #clas, section = #section where studentno = #studentno");
cmd.Parameters.Add(new SqlParameter("name", textBox2.Text));
cmd.Parameters.Add(new SqlParameter("gender", gen));
cmd.Parameters.Add(new SqlParameter("clas", clas));
cmd.Parameters.Add(new SqlParameter("section", section));
cmd.Parameters.Add(new SqlParameter("studentno", textBox1.Text));

How do I make the column type date I want to insert in sql

I want to insert the date format into sql
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Data Source=Server-1;Initial Catalog=Eczane;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO TBL_Musteri (MUSTERI_TC,MUSTERI_AD,MUSTERI_SOYADI,MUSTERI_DOGUM_TARIHI,MUSTERI_CINSIYET,MUSTERI_TELEFON,MUSTERI_ADRES,MUSTERI_IL,MUSTERI_ILCE,MUSTERI_EKLEYEN_ADMIN) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox9.Text + "','" + comboBox1.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Erorr!");
}
}
Use Parameters collection on cmd object.
You can specify the type and the conversion will be done for you. Also it prevents your code from being exposed to SQL injection.
SqlCommand cmd = new SqlCommand("INSERT INTO TBL_Musteri (MUSTERI_TC,MUSTERI_AD,MUSTERI_SOYADI,MUSTERI_DOGUM_TARIHI,
MUSTERI_CINSIYET,MUSTERI_TELEFON,MUSTERI_ADRES,MUSTERI_IL,MUSTERI_ILCE,MUSTERI_EKLEYEN_ADMIN)
VALUES (#param1,#param2,#param3,#param4,#param5,
#param6,#param7,#param8,#param9,#param10)", conn);
cmd.Parameters.Add("#param1", SqlDbType.NVarChar);
cmd.Parameters["#param1"] = textBox1.Text;
...
cmd.Parameters.Add("#param4", SqlDbType.Date;
cmd.Parametes["#param4"] = textBox9.Text;
...

If combobox not selected any item enter empty string into Access database

When I enter a data in my Access database, if I do not select any item in the combobox, I get an error of null exception. So how can I make sure that if I did not select any items, empty data is inserted into my database?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
if (comboBox10.SelectedItem == null)
{
comboBox10.Text = " ";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can check if the SelectedItem property is null, then set a temp variable to use in your query string.
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
Then use comboBox10Text in your query string.
Edit:
// Check if comboBox10.SelectedItem is null, set temp variable
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// Update query string to use comboBox10Text instead of accessing SelectedItem
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can have a null check and change the condition
If(comboBox10.SelectedItem != null)
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
}
else
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + "" + "')";
}

System.Web.UI.WebControls.DataGrid' does not contain a definition for 'Rows'

I got the excel value in gridview and now I need to insert all the values in rows to sql server 2008.
When i try to iterate throught Gridview rows it throws the error in for loop near the dg_AgentSFR.Rows as "DataGrid' does not contain a definition for 'Rows' "
Here is my code:
protected void savedatafromgv()
{
foreach (GridViewRow g1 in ***dg_AgentSFR.Rows)***
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
Please help me to resolve this.
Thanks in advance.
Datagrid does not contain a definition for rows. Instead of rows, it has items.
use this
foreach (DataGridItem Dr in dg_AgentSFR.items)
DataGrid Class
And also use parameterized query to avoid How does SQLParameter prevent SQL Injection
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER....) values (#POL,#POD,#FORWARDER)
try this code
if(dg_AgentSFR.Rows.Count>0)
{
foreach (GridViewRow g1 in dg_AgentSFR.Rows)
{
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = con.CreateCommand();
cmd = new SqlCommand("INSERT INTO TB_TransAgenSeaFreightRate(POL,POD,FORWARDER,FORWARDER REFERENCE,SHIPPING LINE,CONTAINER TYPE,CONTAINER SIZE,VALIDITY FROM,VALIDITY TO,BASIC RATE,PAF,CAF,PSS,TOTAL AMOUNT,REE DAYS,CREDIT DAYS,NIT DEPOSIT,COMPANYID,ISACTIVE) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "','" + g1.Cells[14].Text + "','" + g1.Cells[15].Text + "','" + g1.Cells[16].Text + "',1,'" + TXTCompanyID.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write ("Records inserted successfully");
}
A datagrid in ASP.NET does indeed not contain a property Rows. The GridView on the other hand, does contain a property Rows. More info:
DataGrid class
GridView class
I suggest you use the GridView, this is kind of the successor of the DataGrid. And another important tip: use SQL parameters and not just a string-query (SQL injection).
Make sure you use GridViewRowEventArgs and NOT GridViewCommandEventArgs
protected void gvSample_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Your code here
}

Categories

Resources