I need help with my Microsoft access database assignment using C# on visual studios. I have all the code written, but I keep getting errors on the query message area in the combo box event handler. The error that I keep getting says that I have an issue with the query expression by the zip code table and INNER JOIN area.
Here is the code -
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 Final_Programming
{
public partial class customerInformationFRM : Form
{
public customerInformationFRM()
{
InitializeComponent();
}
OleDbConnection cusInfoConnection = new OleDbConnection();
string chosenCustomer;
// Method for access database connection
private void databaseConnection()
{
try
{
// Establishes where provider to go to in order to open microsoft access file
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"FinalDatabase.accdb;Persist Security Info=False;";
// Open database connection
cusInfoConnection.ConnectionString = connect;
cusInfoConnection.Open();
}
catch (Exception errMsg)
{
// Messagebox pops up if theres an error
MessageBox.Show("Error in databaseConnection method: " + errMsg.Message,
"databaseConnection method error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
// Method to fill combo box
private void fillComboBox()
{
try
{
string cusInfoQRY = "SELECT PersonalInfo.[IDnumber] FROM PersonalInfo";
// Define Adapter
OleDbDataAdapter cusNumDA = new OleDbDataAdapter(cusInfoQRY, cusInfoConnection);
cusNumDA.Fill(cusNumDS, "IDnumber");
cusNumCMB.DataSource = cusNumDS.Tables[0];
cusNumCMB.DisplayMember = "IDnumber";
cusNumCMB.ValueMember = "IDnumber";
}
catch (Exception errMsg)
{
MessageBox.Show("Error in fill combo box method: " + errMsg.Message,
"Combo box error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void customerInformationFRM_Load(object sender, EventArgs e)
{
try
{
databaseConnection();
fillComboBox();
}
catch (Exception errMsg)
{
MessageBox.Show("Error in form load: " + errMsg.Message,
"Form load error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void cusNumCMB_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
cusNumDS.Clear();
customerInfoDS.Clear();
orderInfoDS.Clear();
chosenCustomer = cusNumCMB.Text;
if (chosenCustomer != "System.Data.DataRowView")
{
string cusInfoSQL = "SELECT PersonalInfo.FirstName, PersonalInfo.LastName, PersonalInfo.PhoneNumber, " +
"PersonalInfo.EmailAddress, PersonalInfo.Address, ZipCode.City, ZipCode.State, ZipCode.Zip" +
"FROM ZipCode INNER JOIN PersonalInfo ON ZipCode.[Zip] = PersonalInfo.[Zip] where PersonalInfo.IDnumber = '" +
chosenCustomer + "'";
OleDbDataAdapter customerNumberDA = new OleDbDataAdapter(cusInfoSQL, cusInfoConnection);
customerNumberDA.Fill(customerInfoDS, "customerInfo");
DataRow customerInfoDR = customerInfoDS.Tables[1].Rows[0];
firstNameTB.Text = customerInfoDR[0].ToString();
lastNameTB.Text = customerInfoDR[1].ToString();
phoneNumTB.Text = customerInfoDR[2].ToString();
emailTB.Text = customerInfoDR[3].ToString();
addressTB.Text = customerInfoDR[4].ToString();
cityTB.Text = customerInfoDR[5].ToString();
stateTB.Text = customerInfoDR[6].ToString();
zipTB.Text = customerInfoDR[7].ToString();
string orderSQL = "SELECT OrderInfo.[OrderDate], " +
"OrderInfo.[OrderShipped], OrderInfo.[ShippingFee]FROM OrderInfo where " +
"OrderInfo.[OrderNumber] = '" + chosenCustomer + "'";
OleDbDataAdapter itemsDA = new OleDbDataAdapter(orderSQL, cusInfoConnection);
itemsDA.Fill(orderInfoDS, "order");
decimal total = 0.0m;
foreach (DataRow currentRow in orderInfoDS.Tables[0].Rows)
{
total = Convert.ToDecimal(currentRow[3]);
customerDataDGV.Rows.Add(currentRow[0].ToString(), currentRow[1].ToString(), currentRow[2].ToString(), Convert.ToString(total.ToString("C")));
totalShippingTB.Text = Convert.ToString(total.ToString("C"));
}
}
}
catch (Exception errMsg)
{
MessageBox.Show("Error in combo box event handler: " + errMsg.Message,
"Combo box error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
Related
I have an application that opens a database from a user inputted path, the user then scans a barcode into a textbox and the app should search for this number in the database and return the corresponding row of data. Currently the app works perfectly for Access databases using oleDB and I am writing the code for accessing sqlite databases using sqLite but I am getting an error message from the code Error : unable to open the database. Below is the code, any help appreciated as I am not overly familiar with databases!
private void txtScannedValue_TextChanged(object sender, EventArgs e)
{
if (txtScannedValue.Text.Length == 15)
{
try
{
string dbPath = databasePathBox.Text;
string extension = Path.GetExtension(dbPath);
//open database to read
if (extension == ".mdb" || extension == ".accdb")
{
queryAccessDB(dbPath);
}
else if (extension == ".db")
{
querySqlDB(dbPath);
}
else
{
MessageBox.Show("database extension not recognised");
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
}
public void querySqlDB(string sqlDBpath)
{
// create a new database connection:
string cnctstring = string.Format("data source={0};version=3;new=true;read only=true;", sqlDBpath);
SQLiteConnection sqlite_conn = new SQLiteConnection(cnctstring);
// open the connection:
sqlite_conn.Open();
populateDGVfromSQl(sqlite_conn);
sqlite_conn.Close();
}
public void populateDGVfromSQl(SQLiteConnection sqlite_conn)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "Select * from Production where IMEINumber=$scanned";
sqlite_cmd.Parameters.AddWithValue("$scanned", txtScannedValue.Text);
SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();
while (sqlite_datareader.Read())
{
DataTable dt = new DataTable();
dt.Load(sqlite_datareader);
if (dt.Rows.Count > 0)
{
if (dataGridView1.DataSource != null)
{
((DataTable)dataGridView1.DataSource).ImportRow(dt.Rows[0]);
}
else
{
dataGridView1.DataSource = dt;
}
}
else
{
MessageBox.Show("No Data Found");
}
//reset textBox
txtScannedValue.Text = "";
}
sqlite_conn.Close();
}
catch(SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show("Error 3:" + ex.Message);
}
}
i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}
This program is about inserting expenses someone is making so in the textboxes i have to insert only numbers. So I have to save all those numbers from the textboxes into a txt file, but summed. Can you help me with some ideas?
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text + " " + textBox3.Text + " " + textBox4.Text);
File.WriteAllText(fileName, sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a robust approach to read out numbers from TextBoxes and write them to an output file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
// populate textboxes
var boxs = new[] {textBox1, textBox2};
// get user input
var decimals = new List<decimal>();
var expenses = GetExpenses(boxs, decimals);
if (!expenses)
throw new InvalidOperationException("Expecting numbers");
// write to file
using (var stream = File.Create("output.txt"))
using (var writer = new StreamWriter(stream))
{
foreach (var d in decimals)
{
writer.WriteLine(d);
}
var total = decimals.Sum();
writer.WriteLine("Total: " + total);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private bool GetExpenses(TextBox[] boxs, List<decimal> list)
{
if (boxs == null) throw new ArgumentNullException(nameof(boxs));
if (list == null) throw new ArgumentNullException(nameof(list));
foreach (var box in boxs)
{
var text = box.Text;
decimal result;
if (!decimal.TryParse(text, out result))
return false;
list.Add(result);
}
return true;
}
}
}
You would need a line that adds up the numbers like this:
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text+ " " + textBox3.Text+ " " + textBox4.Text);
sb.AppendLine((Int32.Parse(textBox1.Text) + Int32.Parse(textBox2.Text) + Int32.Parse(textBox3.Text) + Int32.Parse(textBox3.Text)).ToString())
File.WriteAllText(fileName, sb.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Firstly, I would just like to add that I am an absolute beginner at C#, I'm doing my best to learn so I am sorry if this is a noob question, but I have hit a brick wall.
I am working on a program that when finished it will find .DBF files from a specified folder, read the file and insert into a mysql database. I am stuck pretty much at the first hurdle.
I am trying to make the program loop through each file it finds and read them.
I can't seem to be able to access the filename string from the GetFiles() Void.
Is there another way around passing the filename to the queryString rather than specifying it myself?
here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory
.GetFiles(#"C:\Users\74-des\Desktop\", "*.DBF");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine,allFiles);
string filenameWithoutPath = Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\74-des\Desktop\");
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir + ";Extended Properties=dBase IV";
string queryString = "SELECT * FROM " + "test4.DBF";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
ReadData();
}
}
}
you can do the following
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
mDirectory = #"C:\Users\74-des\Desktop\"; // better to use OpenFolderDialog to choose the directory
mFiles = System.IO.Directory.GetFiles(mDirectory, "*.DBF");
if (mFiles.Length > 0)
{
try
{
foreach (string filename in mFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, mFiles);
string filenameWithoutPath = System.IO.Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=dBase IV", mDirectory);
try
{
foreach (var file in mFiles)
{
string queryString = string.Format("SELECT * FROM " + "{0}.DBF", System.IO.Path.GetFileNameWithoutExtension(file));
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(mDirectory))
MessageBox.Show("You should Get Files first!");
else
ReadData();
}
}
}
hope it will help you
I'm developing a simple inventory program that store the hardware devices using C# sql
In my program before I save the record, I want to search for serial number if it exist before I save it or add it in my records to avoid the duplicate, and I receive this exception error:
Syntax error: Missing operand after 'No' operator
Below is my code.
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.SqlClient;
using System.Data.SqlServerCe;
namespace DataBaseApplication
{
public partial class Form1 : Form
{
#region Fields
SqlDataAdapter dataAdapter;
DataSet ds;
// DataRowView drView;
CurrencyManager crmng;
SqlConnection con;
ToolTip tootip;
int inc = 0;
#endregion
public Form1()
{
InitializeComponent();
}
#region Connetion to the DataBase and fill the DataSet Table
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'impiDbDataSet1.Impi' table. You can move, or remove it, as needed.
//this.impiTableAdapter1.Fill(this.impiDbDataSet1.Impi);
// TODO: This line of code loads data into the 'impiDbDataSet.Impi' table. You can move, or remove it, as needed.
//this.impiTableAdapter.Fill(this.impiDbDataSet.Impi);
try
{
string conStrings = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ImpiDb.mdf;Integrated Security=True;Connect Timeout=30";
string sql = "Select * from Impi";
con = new SqlConnection(conStrings);
con.Open();
dataAdapter = new SqlDataAdapter(sql, con);
ds = new DataSet();
dataAdapter.Fill(ds, "Impi");
impdg.DataSource = ds.Tables["Impi"].DefaultView;
crmng = (CurrencyManager)impdg.BindingContext[ds.Tables[0]];
tootip = new ToolTip();
con.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Save the Records to the DataBase
private void btnSave_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
// cb.DataAdapter.Update(ds.Tables["Impi"]);
DataRow dr = ds.Tables["Impi"].NewRow();
dr[0] = txtSerial.Text;
if (txtName.Text != "")
{
dr[1] = txtName.Text;
//Busy trying to solve exception errors and saving the record functionality without duplicating primary key
}
if (cbModel.Text == "MK1" || cbModel.Text == "MK2")
{
dr[2] = cbModel.Text;
}
if (cbStatus.Text == "Serviceble" || cbStatus.Text == "Unserviceble")
{
dr[3] = cbStatus.Text;
}
if (cbDeprtmnt.Text == "AIR" || cbDeprtmnt.Text == "LAND" || cbDeprtmnt.Text == "NAVY" || cbDeprtmnt.Text == "SPECIAL FORCE")
{
dr[4] = cbDeprtmnt.Text;
}
// ds.Tables["Impi"].Rows.Add(dr);
//This is where i stopped trying to figure out how to save my records properly
if (txtSerial.Text.Length!=0)
{
bool search = SearchSerialNumberBeforeSave(txtSerial.Text);
if (search == false)
{
DialogResult dr2 = MessageBox.Show("Are you sure you want to save this serial number", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr2 == DialogResult.Yes)
{
ds.Tables["Impi"].Rows.Add(dr);
dataAdapter.Update(ds, "Impi");
MessageBox.Show("Serial Number Added Successful");
}
// System.Data.SqlClient.SqlCommandBuilder cb;
//cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
} //cb.DataAdapter.Update(ds.Tables["Impi"]);
else
{
MessageBox.Show("This Serial Number Exist and will create the duplicate.\nSerial Number not Saved");
MessageBox.Show("Data Entry was not saved", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please Enter a Impi Serial Number","Data Entry");
txtSerial.Text = "Please Enter Impi Serial Number";
txtSerial.ForeColor = Color.Red;
tootip.SetToolTip(txtSerial, txtSerial.Text);
}
// crmng.Position += 1;
// inc = crmng.Position - 1;
// btnAdd.Enabled = true;
// btnSave.Enabled = false;
if (txtName.Text.Length==0)
{
txtName.Text = "Please Enter the Track Number";
txtName.ForeColor = Color.Red;
tootip.SetToolTip(txtName, txtName.Text);
}
if (cbModel.Text.Length == 0)
{
cbModel.Text = "Please Select the Model Of the device";
cbModel.ForeColor = Color.Red;
tootip.SetToolTip(cbModel, cbModel.Text);
}
if (cbStatus.Text.Length == 0)
{
cbStatus.Text = "Please Select the status of the device";
cbStatus.ForeColor = Color.Red;
tootip.SetToolTip(cbStatus, cbStatus.Text);
}
if (cbDeprtmnt.Text.Length == 0)
{
cbDeprtmnt.Text = "Please Select the assigned department";
cbDeprtmnt.ForeColor = Color.Red;
}
else
{
MessageBox.Show("Data Entry was not Saved", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
#endregion
#region Search Method
public bool SearchSerialNumberBeforeSave(String name)
{
int result = 0;
DataRow[] retRows;
bool val;
//This line of code give this exception error Syntax error: Missing operand after 'No' operator.
retRows = ds.Tables["Impi"].Select("Serial No='" + name + "'");
result = retRows.Length;
if (result > 0)
{
val = true;
}
else
{
val = false;
}
return val;
}
#endregion
}
}
The space in Serial Nois causing this issue.
In order to solve it replace Serial No with [Serial No]
retRows = ds.Tables["Impi"].Select("[Serial No]='" + name + "'");
Take a look at this thread, It asks about the same issue.