I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.
Related
Im writing a code which is saving users from a program in sql tables but when 15 users in one time are saving or updating im getting 1 min delay and program not responding... Can you help me. Its my code.
public bool GetUser(ref clsConnection c)
{
try
{
MySqlConnection connect = new MySqlConnection(connectionMysql);
connect.Open();
MySqlCommand query = new MySqlCommand("SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'", connect);
query.Prepare();
MySqlDataReader dr = query.ExecuteReader();
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
dr.Close();
connect.Close();
return true;
}
}
public void UpdateUser(clsConnection u)
{
MySqlConnection cn = new MySqlConnection(connectionMysql);
try
{
if (u.Username != "")
{
cn.Open();
MySqlCommand query = new MySqlCommand(#"UPDATE Users SET User_Name=#User_Name,User_PlyName=#User_PlyName,User_Cash=#User_Cash,User_Passowrd=#User_Password WHERE User_Name='" + Escape(u.Username) + "';", cn);
if (query != null)
{
query.Parameters.AddWithValue("#User_Name", Escape(u.Username));
query.Parameters.AddWithValue("#User_PlyName", Escape(u.NoColPlyName));
query.Parameters.AddWithValue("#User_Cash", u.Cash);
query.Parameters.AddWithValue("#User_Passowrd", u.Password);
cn.Close();
return;
}
else
{
return;
}
}
}
}
public void AddUser(clsConnection c)
{
try
{
if (c.Username != "")
{
Query(#"INSERT INTO Users (User_Name,User_PlayerName,User_Cash,User_Passowrd) VALUES ('" +
Escape(c.Username) + "', '" +
Escape(c.NoColPlyName) + "', '" +
c.Cash + "', '" +
Espace(c.Passoword) + "');");
}
}
}
//when 15 users try to connect to program program not responding and delay is very big. When <10 users connected to program, program works good,but +10 delay is big...
You should put your query in a using statement like this:
using (MySqlConnection con = new MySqlConnection(connectionMysql))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'";
using (MySqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
return true;
}
}
}
And then you can implement the same method to your UPDATE and INSERT queries
Is there a way to check when an item is entered in a comboBox, is only one in which is actually in the list? To explain further, if anything outside the list is selected it won't accept that input. I've looked within stackoverflow but the only solution am seeing is that of changing my comboBox style to a dropdown list style. The problem with this is that there are more than a hundred records to select from so the autocomplete on the comboBox is absolutely necessary to filter these out by the user input entered.
Updated(declared matched globally):
private void comboBox3_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
matched = items.Any(i => i == c.Text.Trim().ToLower());
}
and this is where it executes:
private void button5_Click(object sender, EventArgs e)
{
if (matched==false)
{
MessageBox.Show("Value in Carimed Items does not exist");
}else
{
if (string.IsNullOrEmpty(comboBox5.Text))
{
MessageBox.Show("Please select output file to be written to!");
}
else
{
// int current = 0;
if (comboBox1.Text.Trim() == string.Empty)
{
MessageBox.Show("All fields must be filled in before saving!");
}
else
{
// StringBuilder csvconten = new StringBuilder();
// csvconten.AppendFormat("{0},{1},{2},{3},{4},{5}\r\n", comboBox2.Text, textBox5.Text, textBox2.Text, comboBox3.Text, textBox3.Text, comboBox1.Text);
// string csvpath = "cross_check.csv";
// File.AppendAllText(csvpath, csvconten.ToString());
string connectionString3 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacy_Output_File;Integrated Security=True";
string query3 = "INSERT INTO dbo.[" + comboBox5.Text + "] VALUES('" + comboBox2.Text + "','" + textBox5.Text.Replace("'", "''") + "','" + textBox7.Text.Replace("'", "''") + "','" + textBox2.Text.Replace("'", "''") + "','" + comboBox3.Text.Replace("'", "''") + "','" + textBox3.Text + "','" + comboBox1.Text + "');";
using (SqlConnection connection = new SqlConnection(connectionString3))
{
SqlCommand command = new SqlCommand(query3, connection);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
// textBox1.Clear();
// textBox3.Clear();
// comboBox3.ResetText();
textBox2.Clear();
textBox3.Clear();
comboBox3.ResetText();
comboBox1.ResetText();
}
string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query2 = "UPDATE Liguanea_Lane2 SET Progress= '1' where code = '" + comboBox2.Text + "'; ";
using (SqlConnection connection = new SqlConnection(connectionString2))
{
SqlCommand command = new SqlCommand(query2, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//this.liguanea_ProgressTableAdapter1.Fill(this.pharmaciesDataSet7.Liguanea_Progress);
comboBox2.SelectedIndex = comboBox2.SelectedIndex + 1;
//current = liguaneaLane2BindingSource.Position;
//this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
refreshDataGrid2();
if (dataGridView1.CurrentRow != null)
{
dataGridView1.CurrentCell =
dataGridView1
.Rows[Math.Min(dataGridView1.CurrentRow.Index + 1, dataGridView1.Rows.Count - 1)]
.Cells[dataGridView1.CurrentCell.ColumnIndex];
// liguaneaLane2BindingSource.Position = Math.Min(current + 1, liguaneaLane2BindingSource.Count - 1);
}
}
}
}
You can Use the TextChanged Event of the ComboBox to See if the enter text exsists in you list:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
bool matched = items.Any(i => i == c.Text.Trim().ToLower());
}
You can declare the matched bool globally in the form that TextChanged event would assign its value then you can use it in other Methods like:
void Button_Click(object sender, e EventArgs){
if(matched)
{
//do something
} else{
// show an error message
}
}
I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
C# having some errors from fetching
public partial class BioreCottonPurchaseSlip2011 : Form
{
Library obj = new Library();
public BioreCottonPurchaseSlip2011()
{
InitializeComponent();
}
public void enableDisableControls(bool flag)
{
TxtExtensionNo.Enabled = flag;
TxtFarmerCode.Enabled = flag;
TxtFarmerName.Enabled = flag;
TxtBasicPrice.Enabled = flag;
TxtPremium.Enabled = flag;
TxtWeight.Enabled = flag;
TxtTotalAmountBasic.Enabled = flag;
TxtTotalAmountPremium.Enabled = flag;
TxtBalancePay.Enabled = flag;
BtnSave.Enabled = flag;
BtnCancel.Enabled = flag;
}
public void clearControls()
{
TxtExtensionNo.Text = "";
TxtFarmerCode.Text = "";
TxtFarmerName.Text = "";
TxtBasicPrice.Text = "";
TxtPremium.Text = "";
TxtWeight.Text = "";
TxtTotalAmountBasic.Text = "";
TxtTotalAmountPremium.Text = "";
TxtBalancePay.Text = "";
}
private void BtnNew_Click(object sender, EventArgs e)
{
if (obj.GetConnection() == true)
{
lblError.Text = "Connected !!!";
}
else
{
lblError.Text = "Not connnected !!!";
}
enableDisableControls(true);
BtnNew.Enabled = false;
// lblError.Text = "";
string connectionString = "Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True";
string sql = "SELECT * FROM cottonpurchase";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds, "cottonpurchase");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "cottonpurchase";
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (obj.GetConnection() == true)
{
//dateTimePicker1.Value = DateTime.Today;
MessageBox.Show("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + ")");
if (obj.ExecuteSQLStatement("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + " )") == true)
{
lblError.Text = "Item(s) Saved";
clearControls();
BtnSave.Enabled = false;
BtnNew.Enabled = true;
enableDisableControls(false);
}
else
{
lblError.Text = "Item(s) Not Saved";
}
}
else
{
lblError.Text = "Connection Error. Please contact your administrator.";
}
enableDisableControls(false);
clearControls();
BtnNew.Enabled = true;
try
{
//double getvat = 0;
//double calculatevat = 0;
//getvat = Convert.ToDouble(TxtTotalAmountBasic.Text);
//calculatevat = getvat * 0.18;
//TxtBasicPrice.Text = calculatevat.ToString();
//TxtBasicPrice.Enabled = false;
}
catch (Exception)
{
// lblError.Text = "Please contact your administrator. (Error - TARS0001DATMIS)";
clearControls();
enableDisableControls(false);
BtnNew.Enabled = true;
//lblInvoiceNo.Text = "INVOIC NO";
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
enableDisableControls(false);
clearControls();
BtnNew.Enabled = true;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void TxtFarmerCode_TextChanged(object sender, EventArgs e)
{
try
{
SqlConnection conn= new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
conn.Open();
cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=#aa", conn);
cmd.Parameters.Add("#aa", SqlDbType.Int).Value = TxtFarmerCode.Text;
dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
// textBox1.Text = dr[0].ToString(); Since U r going to give the ID and retrieve in textBox1.
TxtFarmerName.Text = dr[0].ToString();
//textBox3.Text = dr[1].ToString();
//textBox4.Text = dr[2].ToString();
//textBox7.Text = dr[3].ToString();
//dateTimePicker1.Text = dr[4].ToString();
//dateTimePicker2.Text = dr[5].ToString();
//textBox5.Text = dr[6].ToString();
}
}
catch
{
// lblError = "THE GIVEN ID IS UNAVAILABLE";
}
finally
{
conn.Close();
}
}
}
You have to define your variable types
SqlCommand cmd = new SqlCommand(...);
SqlReader dr = cmd.ExecuteReader();
In TxtFarmerCode_TextChanged, you haven't defined the variables cmd or dr.
You'll want something like this:
SqlCommand cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=#aa", conn);
[...]
SqlDataReader dr = cmd.ExecuteReader();
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();