CheckBox Not Sending Checked Value to Access Database C# Asp - c#

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() + "')";

Related

I am getting Datatype mismatch error due to blank cells in DataGridView

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();
}

error insert query after install application

i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}​

trying to create a refreshing button for gridview

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();

On load event problem

I have a problem when I want to update a row in a database. The page that updates also adds a client but the problem is that when page load detects update button was pressed it seems to keep loading up the variables and I am unable to update my database.
public partial class CustomerInput : System.Web.UI.Page
{
string update, Id, Name, Address, Suburb, Postcode, Age, Email;
protected void Page_Load(object sender, EventArgs e)
{
update = Request.QueryString["Update"];
if (update == "true")
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
Button1.Text = "Update";
Id = Request.QueryString["Id"];
connection.Open();
SqlCommand command = new SqlCommand("Select * from Customer where Id = " + Id, connection);
SqlDataReader read = command.ExecuteReader();
read.Read();
TextBox1.Text = read[1].ToString();
TextBox2.Text = read[2].ToString();
TextBox3.Text = read[3].ToString();
TextBox4.Text = read[4].ToString();
TextBox5.Text = read[5].ToString();
TextBox6.Text = read[6].ToString();
connection.Close();
update = string.Empty;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
if (Button1.Text == "Update")
{
connection.Open();
SqlCommand command;
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
command = new SqlCommand("UPDATE Customer SET Name = " + "'" + Name + "', " + "Address = " + "'" + Address + "', " + "Suburb = " + "'" + Suburb + "', "
+ "Postcode = " + "'" + Postcode + "', " + "Age = " + "'" + Age + "', " + "Email = " + "'" + Email + "' " + "Where Id =" + Id, connection);
command.ExecuteNonQuery();
connection.Close();
}
if (Button1.Text == "New Client")
{
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
Response.Write("Blah");
SqlCommand command = new SqlCommand("INSERT INTO Customer VALUES (" + "'" + Name + "'" + ", " + "'" + Address + "'" + ", " + "'" + Suburb + "'" + ", "
+ "'" + Postcode + "'" + ", " + "'" + Age + "'" + ", " + "'" + Email + "'" + ")", connection);
command.ExecuteNonQuery();
}
Button1.Text = "New Client";
}
}
}
At the start of your page load event you need to add an if statement to check if this is the first time the page loads:
example:
if (!IsPostBack)
{
... add your code here
}
I guess you need to use Page.IsPostBack:
if (Page.IsPostBack)
{
// Do Something ..
{
else
{
// Do something else ..
}

how to insert data if it contain apostrophe?

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();

Categories

Resources