Insert button in C# and SQL Server - c#

I'm trying to fix the code of an insert button. It's a button that inserts data into the database.
Here is my code :
private void button2_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
sqlCon.Open();
// string requete = "INSERT INTO [RECAP] VALUES ('" + textBox1.Text + "''" + textBox2.Text + "''" + comboBox2.SelectedValue + "''" + comboBox3.SelectedValue + "''" + textBox5.Text + "''" + textBox6.Text + "''" + Global.Global.GolbVar + "''" + DateTime.Now.ToShortDateString() + "');";
string requete = "INSERT INTO dbo.RECAP(code_reseau, tot_dcl, mont_debou, gch_dep, typ_port, mois, annee, emt_dep, utilisateur, date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";
cmd = new SqlCommand(requete, sqlCon);
cmd.ExecuteNonQuery();
MessageBox.Show("Ajouté !");
sqlCon.Close();
}
Every time I try to run this it generates an exception that says
Incorrect syntax near ','

Try replacing
string requete = "INSERT INTO dbo.RECAP(code_reseau,tot_dcl,mont_debou,gch_dep,typ_port,mois, annee, emt_dep,utilisateur,date_maj) VALUES ('" + textBox1.Text + "', " + textBox5.Text + "," + textBox6.Text + "," + comboBox2.SelectedValue + "," + comboBox3.SelectedValue + "," +0+ "," +0+ "," +0+ "," + 0 + "," + 0 + ")";
with
SqlCommand com = new SqlCommand("INSERT INTO RECAP (code_reseau, tot_dcl, mont_debou, gch_dep, typ_port,mois, annee, emt_dep, utilisateur, date_maj) VALUES(#txt1, #txt5, #txt6, ,#combo2, #combo3, 0, 0, 0, 0, 0)", sqlCon);
com.Parameters.AddWithValue("#txt1", textBox1.Text);
com.Parameters.AddWithValue("#txt5", textBox5.Text);
com.Parameters.AddWithValue("#txt6", textBox6.Text);
com.Parameters.AddWithValue("#combo2", comboBox2.SelectedValue);
com.Parameters.AddWithValue("#combo3", comboBox3.SelectedValue);
and see if that works

Check if the below
textBox5.Text
textBox6.Text
comboBox2.SelectedValue
comboBox3.SelectedValue
are all numeric type.
As they are not passed in single quotes, so either their values should be convertible to a number (and the respective column is also of that type) or they are causing the error as some text is inserted in the SQL statement without any quotes around it.

Related

How to fix "Invalid Column Name" SQL Exception on MSSQL

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?

How can i get result in two data table after execute the Query?

After execution result is coming in two select statement. How can get in two different data table by c#?
using (SqlConnection con = new SqlConnection(sqlConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Exec SPSearchInvoiceList_rjt " + _customerID + "," + _ProjectInchargeID + "," + _projectID +
"," + _invoiceType + ",'" + _projectTypes + "'," + _invoiceAmount + ",'" + _invoiceCode +
"'," + _invoiceStatusID + ",'" + _invoiceDateFrom + "','" + _invoiceDateTo + "','" +
_invoiceRevisedDateFrom + "','" + _invoiceRevisedDateTo + "','" + _invoiceRaiseDateFrom +
"','" + _invoiceRaiseDateTo + "'," + Convert.ToInt32(PageIndex) + 1 + "," + pageSize;
cmd.Connection = con;
con.Open();
var datareader = cmd.ExecuteReader();
con.Close();
}
}
I am trying to do it as above.I am unable to get records but i am able to get data once i execute commandtext in sql server. Please help.

Adding data to database from frontend to backend

I'm getting this error code: "unclosed quotation mark after the character string" on the line: cmd.ExecuteNonQuery();
I've looked, but I don't know what's wrong. I also tried just putting two of the textboxe, but I can't seem to debug it. Please advise. Thanks!
Here's the code:
namespace Inventory
{
public partial class NewData : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection("Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234");
protected void Page_Load(object sender, EventArgs e)
{
}//end page load
protected void addButton_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" + Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
cmd.ExecuteNonQuery();
cn.Close();
status.Visible = true;
status.Text = "Added succesffully!";
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//end add button
protected void clearButton_Click1(object sender, EventArgs e)
{
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//clear button
}//end
}//end
As far as I can see, you have unnecessary single quote at the end of your query.
Notestb.Text + "')'
^^ here
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var cn = new SqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
// Set your CommandText property with your parameter definitions
// Add your parameters and their values with Add method
// Open your connection
// Execute your query.
}
Your command ends with an extra single quote. It should be:
cmd.CommandText = "INSERT INTO Inventory values('" +
Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text +
"','" + Serialtb.Text + "','" + Assignedtb.Text + "','" +
Locationtb.Text + "','" + Notestb.Text + "')";
I think the problem is
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" +
Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
there you single comma ' after the right bracket ).
Should have been:
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','"
+ Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text
+ "')";

how to store the values into data table which are entered in grid view? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to insert the values entered in data grid view in a data table..
I tried with code..
private void btnSave_Click(object sender, EventArgs e)
{
billNO++;
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE [" + "" + combCustomerName.Text + "] (SlNO int Not Null , ItemDesc varchar(100) , ItemDetails varchar(100) , UMO varchar(10) , Quntity numeric(10,3) , Rate numeric(10,2) , Amount numeric(10,2) , GrossTot numeric(10,2) , Discount numeric(7,2) , Taxpc numeric(5,2) , TaxAmt numeric(5,2) , OtherAmt numeric(7,2) , NetAmt numeric(10,2))";
SqlCommand cmd = new SqlCommand(s, con);
cmd.ExecuteNonQuery();
//string insert=null;
SqlCommand inscmd = new SqlCommand();
for (int i = 0; i < datagridItemEntry.Rows.Count; i++)
{
inscmd.CommandText = "INSERT INTO [" + "" + combCustomerName.Text + "] VALUES(" + datagridItemEntry.Rows[i].Cells[0].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[1].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[2].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[3].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[4].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[5].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[6].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[7].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[8].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[9].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[10].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[11].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[12].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[13].Value.ToString() + "')";
}
if (inscmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("Done!");
}
con.Close();
}
It is creating the table..
I am getting exception as Index out of range while inserting..
Help me out.
Just Copy Paste this code after your first query got executed.
for (int i = 0; i < datagridItemEntry.Rows.Count; i++)
{
string query1 = "insert into "+combCustomerName.Text+" values(" + gvSalesInv.Rows[i].Cells[0].Value + "," + gvSalesInv.Rows[i].Cells[1].Value + "," + gvSalesInv.Rows[i].Cells[2].Value + "," + gvSalesInv.Rows[i].Cells[3].Value + "," + gvSalesInv.Rows[i].Cells[4].Value + "," + gvSalesInv.Rows[i].Cells[5].Value + "," + gvSalesInv.Rows[i].Cells[6].Value + "," + gvSalesInv.Rows[i].Cells[7].Value + "," + gvSalesInv.Rows[i].Cells[8].Value + "," + gvSalesInv.Rows[i].Cells[9].Value + "," + gvSalesInv.Rows[i].Cells[10].Value + "," + gvSalesInv.Rows[i].Cells[11].Value + ")";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.ExecuteNonQuery();
}

Data not inserting in c# but same data is inserted in SQL Server query browser

I have a link button in my gridview at which I have some to insert value in table but it is not inserting but query data on debug mode when I tested on SQL Server it is inserted so whats the problem
protected void gvPO_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
c.GetConection();
SqlCommand cmd = new SqlCommand("delete from tmpMateIN", c.con);
cmd.ExecuteNonQuery();
DataTable dt;
int index = Convert.ToInt32(e.CommandArgument);
gvPO.SelectedIndex = index;
if (Convert.ToInt16(gvPO.SelectedIndex) < 0)
{
lblMsg.Text = "Please Select Code !";
return;
}
dt = oAccount.GetPO((int)Session["CompCode"], 79, Convert.ToInt16(((LinkButton)gvPO.Rows[gvPO.SelectedIndex].Cells[0].FindControl("lnkCode")).Text.ToString()));
for (int i = 0; i < dt.Rows.Count; i++)
{
String s6 = "insert into tmpMateIN(compcode ,msttype ,mstcode,mstdate ,mstchno ,mstblno ,mstbldt ,mstcust ,itdsrno , itditem ,itdquan ,itdrema ,itemname ,acctname ,ItmSize , unitname ,itemsize ,chno , chdt ,godown, packsize ,itdRate , itdDisc , itdAmou , mstInvNo , mstOrdNo,mstInvDt ,mstOrdDt ,mstrema , mstexcDes , msttaxDes ,msttaxper , mstfrghtDes , mstfrghtper , mstdeliDes ,mstpayDes , mstvaliDes, mstqno, mstqdt , itdthickness , itdlength ,itdwidth ,itdweight, itdtowt , acctaddr , custemail , mstpayMode , mstdepa,itdrefq,itdorgq)values(" + (int)Session["CompCode"] + ",79,'" + dt.Rows[i]["mstcode"] + "','" + dt.Rows[i]["mstdate"] + "'," + dt.Rows[i]["mstchno"] + ",'" + dt.Rows[i]["mstchno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstptcode"] + "','" + (i + 1) + "','" + dt.Rows[i]["itditem"] + "','" + dt.Rows[i]["itdquan"] + "','" + dt.Rows[i]["itdrema"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["AcctName"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["UnitName"] + "' ,'" + dt.Rows[i]["itdunit"] + "','','" + dt.Rows[i]["mstdate"] + "','',''," + dt.Rows[i]["itdRate"] + "," + dt.Rows[i]["itdamou"] + " ," + dt.Rows[i]["itdAmou"] + ",'" + dt.Rows[i]["mstInvNo"] + "','" + dt.Rows[i]["mstindno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstrema"] + "','','','" + dt.Rows[i]["mstTaxPer"] + "','" + dt.Rows[i]["mstfrghtDes"] + "','" + dt.Rows[i]["mstfrghtper"] + "','" + dt.Rows[i]["mstdeliDes"] + "','" + dt.Rows[i]["mstpayDes"] + "','" + dt.Rows[i]["mstvaliDes"] + "','" + dt.Rows[i]["mstqno"] + "','" + dt.Rows[i]["mstpodate"] + "','" + dt.Rows[i]["itdthickness"] + "','" + dt.Rows[i]["itdsource"] + "','" + dt.Rows[i]["itddestin"] + "','" + dt.Rows[i]["itdweight"] + "','" + dt.Rows[i]["itdtowt"] + "','','" + dt.Rows[i]["acctaddr"] + "','" + dt.Rows[i]["mstpayMode"] + "','" + dt.Rows[i]["mstContactPerson"] + "','" + dt.Rows[i]["mstlotno"] + "','" + dt.Rows[i]["mstsection"] + "' )";
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.ExecuteNonQuery();
}
c.CloseConnection();
Response.Redirect("Poreport.aspx");
}
}
You can run the SQL Server Profiler to see if the call is made to SQL Server for insertion at the time of execution of your program.
Suggestion: Why don't you use stored procedure instead of having this inline query this way:
var dr = dt.Rows[i];
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "tmpMateIN_Insert";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();
ADDED:
OR if you really want to stick with an inline query then preferred approach is to use parameterized inline query as shown below:
String s6 = "insert into tmpMateIN(compcode, msttype, mstcode, mstdate, ..." +
"values(#compcode, #msttype, #mstcode, #mstdate, ...";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();

Categories