I have made an c# program to access a database and write some data to it, and show it in a grid-view.
That all works but now i want the grid-view to refresh because it wont show the data i just entered into the database
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace ForexDev
{
public partial class Form1 : Form
{
private OleDbConnection Database1;
private OleDbCommand oledbcmd = new OleDbCommand();
private string connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
public Form1()
{
Database1 = new OleDbConnection(connParam);
InitializeComponent();
}
private void btnsave_Click(object sender, EventArgs e)
{
try
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = "INSERT INTO Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.Refresh();
dataGridView1.Update();
Database1.Close();
if (temp > 0)
{
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Failed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database11DataSet.Forex' table. You can move, or remove it, as needed.
this.forexTableAdapter.Fill(this.database11DataSet.Forex);
}
private void button2_Click(object sender, EventArgs e)
{
Database1.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Database1.Open();
this.dataGridView1.Refresh();
this.dataGridView1.Update();
Database1.Close();
}
}
}
I want to thank you tariq for putting me on the right track, i did not mark your answer as the answer to my problem because of the following :
The answer to my problem was that i needed to bind the database to the gridview like this :
(and correct me if this is not databinding)
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = textBox1.Text;
oledbcmd.CommandText = "DELETE FROM Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.DataSource = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
dataGridView1.Refresh();
this.dataGridView1.Refresh();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter dd = new OleDbDataAdapter();
dd = new OleDbDataAdapter("Select * From Forex", Database1);
dd.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
Database1.Close();
Add this after making updates
dataGridView1.DataBind();
Related
I have a code that takes data from excel to DataGridView and then from there saves on to an access database. I think my code is good but i keep getting
"Datatype mismatch"
I believe it is because of the the blank cells in the DataGridView. Can someone please suggest a different approach? Thanks
private void btn_sal2_Click(object sender, EventArgs e)
{
OleDbConnection cnEMP2 = new OleDbConnection();
cnEMP2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\SWFAL\Desktop\McDat2019.mdb";
cnEMP2.Open();
using (OleDbCommand cmdEMP2 = new OleDbCommand())
{
foreach (DataGridViewRow EMPRow in this.dgvsal.Rows)
{
for (int i = 0; i <= EMPRow.Cells.Count; i++)
{
if (EMPRow.Cells[i].Value != null || !string.IsNullOrWhiteSpace(Convert.ToString(EMPRow.Cells[i].Value)))
{
cmdEMP2.Connection = cnEMP2;
string qryEMP = "UPDATE Salinity2 set Texture='" + Convert.ToString(EMPRow.Cells[1].Value) + "', EC='" + Convert.ToString(EMPRow.Cells[2].Value) + "', Cl='" + Convert.ToString(EMPRow.Cells[3].Value) + "', NO3N='" + Convert.ToString(EMPRow.Cells[4].Value) + "', pH='" + Convert.ToString(EMPRow.Cells[5].Value) + "', CO3='" + Convert.ToString(EMPRow.Cells[6].Value) + "', HCO3='" + Convert.ToString(EMPRow.Cells[7].Value) + "', Volume='" + Convert.ToString(EMPRow.Cells[8].Value) + "', [NH4-N]='" + Convert.ToString(EMPRow.Cells[9].Value) + "', Na='" + Convert.ToString(EMPRow.Cells[10].Value) + "', Ca='" + Convert.ToString(EMPRow.Cells[11].Value) + "', Mg='" + Convert.ToString(EMPRow.Cells[12].Value) + "', K='" + Convert.ToString(EMPRow.Cells[13].Value) + "', SO4='" + Convert.ToString(EMPRow.Cells[14].Value) + "', Boron='" + Convert.ToString(EMPRow.Cells[15].Value) + "', [ICAP-P]='" + Convert.ToString(EMPRow.Cells[16].Value) + "', Fe='" + Convert.ToString(EMPRow.Cells[17].Value) + "', Zn='" + Convert.ToString(EMPRow.Cells[18].Value) + "', Cu='" + Convert.ToString(EMPRow.Cells[19].Value) + "', Mn='" + Convert.ToString(EMPRow.Cells[20].Value) + "' where LabID=" + Convert.ToInt32(EMPRow.Cells[0].Value) + " ";
cmdEMP2.CommandText = qryEMP;
cmdEMP2.CommandType = CommandType.Text;
cmdEMP2.ExecuteNonQuery();
}
else
{
}
}
}
}
To load from Excel into a dataset, try the following.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
To export from datagridview to MS Access.
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
I am having an issue with a datagrid and and getting it to refresh when new data is added. The way I am trying to get it to work is.
On main form, a button("add") click event which shows a form2 with fields to input the new data into the table which is in main form. Once the data is entered and then a button("Insert/Add") click event which closes form2 and display that new entered data in main form data grid.
The problem is that I do not know exactly how the datagrid be refresh or update to show the new information. Any help would be appreciated.
MAIN FORM:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WindowsFormsApplication2
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'userLoginDataSet.WeaponData' table. You can move, or remove it, as needed.
this.weaponDataTableAdapter.Fill(this.userLoginDataSet.WeaponData);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
AddWeapon aw = new AddWeapon();
aw.Show();
}
}
}
ADDWEAPON FORM:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using Microsoft.Win32;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class AddWeapon : Form
{
public AddWeapon()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\brmcbrid\Documents\Visual Studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\UserLogin.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT into WeaponData values('" + serialNumber.Text + "','" + brand.Text + "','" + model.Text + "','" + caliber.Text + "','" + type.Text + "' , '" + dateAcquired.Text + "', '" + dateSold.Text + "', '" + purchasePrice.Text + "', '" + sellPrice.Text + "', '" + notes.Text + "')", con);
this.Close();
}
}
}
There are several options you have. All of them deal with having a reference of the main form in the child form.
Option #1:
Pass the Main form instance as a constructor in the child form:
In Main form code:
AddWeapon aw = new AddWeapon(this); // pass this, the main form
aw.Show();
In child form, have a private field of the main form and an additional constructor.
public partial class AddWeapon : Form
{
private Main _mainForm;
public AddWeapon()
{
InitializeComponent();
}
public AddWeapon(Main mainForm) : this()
{
this._mainForm = mainForm;
}
// remaining code.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\brmcbrid\Documents\Visual Studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\UserLogin.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT into WeaponData values('" + serialNumber.Text + "','" + brand.Text + "','" + model.Text + "','" + caliber.Text + "','" + type.Text + "' , '" + dateAcquired.Text + "', '" + dateSold.Text + "', '" + purchasePrice.Text + "', '" + sellPrice.Text + "', '" + notes.Text + "')", con);
// call a public method on the main form that can update the data.
this._mainForm.UpdateData();
this.Close();
}
}
Option #2:
Instead of passing the reference of the main form in the constructor, you could also set it via a public property of the child form and do the same.
AddWeapon aw = new AddWeapon();
aw.Main = this;
aw.Show();
Option #3:
This option has no form instance connection. What you do is raise an event when the child form has inserted the data and have the parent form subscribe to this event.
in the parent form
AddWeapon aw = new AddWeapon();
aw.OnDataInserted += this.DataInserted;
aw.Show();
in the child form,
public event EventHandler DataInserted;
and then after the insert
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\brmcbrid\Documents\Visual Studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\UserLogin.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT into WeaponData values('" + serialNumber.Text + "','" + brand.Text + "','" + model.Text + "','" + caliber.Text + "','" + type.Text + "' , '" + dateAcquired.Text + "', '" + dateSold.Text + "', '" + purchasePrice.Text + "', '" + sellPrice.Text + "', '" + notes.Text + "')", con);
if (this.DataInserted != null)
{
this.DataInserted();
}
this.Close();
}
You can write code to refresh your grid on activate event of Main form as shown below:
private void Main_Activated(object sender, EventArgs e)
{
// write your code here
}
im currently in my first year on university and c# is relatively new to me.
im currently working on accessing a database through a form for a made up company for one of my assignments and I cant get through an error that returns saying that myReader is trying to find the database called Jap1.mdb even though the database I have it linked to and successfully connecting to called Jap1.accdb.
the connection to the database works fine as I have a datagrid that produces all the information in the database and allows me to search through it so I am unsure as to why it is trying to find Jap1.mdb
this is the code I currently have in my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace customer_play
{
public partial class customersfrm : Form
{
OleDbConnection myConn;
OleDbDataAdapter myDataAdapter;
OleDbCommandBuilder cb;
DataSet ds;
string myConnection;
public customersfrm()
{
InitializeComponent();
}
private void customersfrm_Load(object sender, EventArgs e)
{
myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "jap1.accdb";
myConn = new OleDbConnection(myConnection);
myDataAdapter = new OleDbDataAdapter();
myDataAdapter.SelectCommand = new OleDbCommand(" select * Jap1.CustomerDetails ;", myConn);
cb = new OleDbCommandBuilder(myDataAdapter);
myConn.Open();
ds = new DataSet();
myConn.Close();
}
private void addcustbtn_Click(object sender, EventArgs e)
{
string Query = "insert into Jap1.CustomerDetails (myFirstName,mySecondName,myAddress,myCity,myPostCode,myNumber,myEmailAddress,myDateOfBirth,my18Plus) values('" + this.firstnametxt.Text + "','" + this.secondnametxt.Text + "', '" + this.addresstxt.Text + "', '" + this.citytxt.Text + "', '" + this.postcodetxt.Text + "', '" + this.numbertxt.Text + "', '" + this.emailtxt.Text + "', '" + this.dobpicker.Text + "', '" + this.eighteenchkbx.Checked + "') ;";
OleDbCommand cmdDataBase = new OleDbCommand(Query, myConn);
OleDbDataReader myReader;
try {
myConn.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("New Customer Has Been Added To The Database");
firstnametxt.Text = "";
secondnametxt.Text = "";
addresstxt.Text = "";
citytxt.Text = "";
postcodetxt.Text = "";
numbertxt.Text = "";
emailtxt.Text = "";
dobpicker.Text = "";
eighteenchkbx.Text = "";
while(myReader.Read()){
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
}
any help would be hugely appreciated :)
Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace tool
{
public partial class Form1 : Form
{
StreamReader reader;
SqlConnection con;
SqlCommand cmd;
int count = 0;
//int id=0;
FileStream fs;
string file = null;
string file_path = null;
SqlCommand sql_del = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog();
file1.ShowDialog();
textBox1.Text = file1.FileName.ToString();
file = Path.GetFileName(textBox1.Text);
file_path = textBox1.Text;
fs = new FileStream(file_path, FileMode.Open, FileAccess.Read);
}
private void button2_Click(object sender, EventArgs e)
{
if (file != null )
{
sql_del = new SqlCommand("Delete From credit_debit1", con);
sql_del.ExecuteNonQuery();
reader = new StreamReader(file_path);
string line_content = null;
string[] items = new string[] { };
while ((line_content = reader.ReadLine()) != null)
{
if (count >=4680)
{
items = line_content.Split(',');
string region = items[0].Trim('"');
string station = items[1].Trim('"');
string ponumber = items[2].Trim('"');
string invoicenumber = items[3].Trim('"');
string invoicetype = items[4].Trim('"');
string filern = items[5].Trim('"');
string client = items[6].Trim('"');
string origin = items[7].Trim('"');
string destination = items[8].Trim('"');
string agingdate = items[9].Trim('"');
string activitydate = items[10].Trim('"');
if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber)))
{
invoicenumber = "null";
}
else
{
invoicenumber = "'" + invoicenumber + "'";
}
if ((destination == "-") || (string.IsNullOrEmpty(destination)))
{
destination = "null";
}
else
{
destination = "'" + destination + "'";
}
string vendornumber = items[11].Trim('"');
string vendorname = items[12].Trim('"');
string vendorsite = items[13].Trim('"');
string vendorref = items[14].Trim('"');
string subaccount = items[15].Trim('"');
string osdaye = items[16].Trim('"');
string osaa = items[17].Trim('"');
string osda = items[18].Trim('"');
string our = items[19].Trim('"');
string squery = "INSERT INTO credit_debit1" +
"([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " +
"[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " +
"[OverUnderRecovery] ) " +
"VALUES " +
"('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," +
"'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," +
"'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') ";
cmd = new SqlCommand(squery, con);
cmd.CommandTimeout = 1500;
cmd.ExecuteNonQuery();
}
label2.Text = count.ToString();
Application.DoEvents();
count++;
}
MessageBox.Show("Process completed");
}
else
{
MessageBox.Show("path select");
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;");
con.Open();
}
}
}
vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data
Use prepared statements, in this case SqlParameterCollection.AddWithValue or equivalent. There are a variety of tutorials available for this.
You are very naughty for building your sql statements that way, Santa Claus is definitely not going to visit you this year. Doing queries the way you are is opening yourself to sql injection attacks, intentional and unintentional as you've discovered with the '.
You should use parameterized query strings or stored procedures.
const string connString = "Data Source=localhost;Initial Catalog=OnlineQuiz;Integrated Security=True";
static void Main(string[] args)
{
string query = string.Format("SELECT * FROM [User] WHERE name like #name");
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#name", "F%");
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetValue(1));
}
}
}
}
}
You need to escape the apostrophe by adding a second apostrophe:
vendorname = vendorname.Replace("'", "''");
Disclaimer: Writing a raw SQL statement without using parameters is dangerous. Ideally, you should write a full SQL insert statement with assumed parameters, and instead of concatenating the value directly into the string, pass it in as a parameter:
string parameterizedSQL = "insert into credit_debit1 (id,region,station) values (#count, #region,#station)";
SqlCommand cmd = new SqlCommand(parameterizedSQL, con);
cmd.Parameters.Add("#count", SqlDbType.Int).Value = count;
cmd.Parameters.Add("#region", SqlDbType.VarChar).Value = region;
cmd.Parameters.Add("#station", SqlDbType.VarChar).Value = station;
cmd.ExecuteNonQuery();