Update Database with Textboxes - c#

I'm trying to get these textboxes to show data from a database, i'm able to show the data but everytime I try to update it won't save. Here's what i've done
private void ClubRecord_Load(object sender, EventArgs e)
{
try
{
sConnection = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = Eastern_Property_Maintenance.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Club ORDER BY CompanyName, CompanyAddress, CompanyPhone;";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbreader = dbCmd.ExecuteReader();
while (dbreader.Read())
{
string CompanyName = dbreader["CompanyName"].ToString();
string CompanyAddress = dbreader["CompanyAddress"].ToString();
string CompanyPhone = dbreader["CompanyPhone"].ToString();
txtCompanyName.Text = CompanyName;
txtCompanyAddress.Text = CompanyAddress;
txtCompanyPhone.Text = CompanyPhone;
}
dbreader.Close();
// dbConn.Close();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = "UPDATE [Club] SET [CompanyName]= #CompanyName,[CompanyAddress]=#CompanyAddress,[CompanyPhone]=#CompanyPhone";
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
Any help would be greatly appreciated thanks.

It is a subtle typo error, but I think that there is something to learn here, so I want to give a full answer:
You create a command called dbcmd
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
but then you fill the parameter collection of a different command dbCmd and executes this one.
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
C# is case sensitive, so the twos are not the same command, but how does it lead to the failed update is worth to look at.
You have declared a global OleDbCommand variable named dbCmd and this variable is still set to the SELECT query used to load the textboxes. So, when you call ExecuteNonQuery it does not update anything.
You could fix the problem simply changing all the references in the updated code from dbCmd to dbcmd. But, the lesson to learn here is, when possible avoid to use global variables.
The Connection is another example of a global variable and this is worst because it is left open after the initial form load. Don't do that. Connectiosn keep valuable system resources locked and thus should be closed immediately after usage applying the using statement pattern
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = #"UPDATE [Club] SET [CompanyName]= #CompanyName,
[CompanyAddress]=#CompanyAddress,
[CompanyPhone]=#CompanyPhone"; // A where here should be mandatory
using(OleDbConnection dbConn = new OleDbConnection(aGlobalConnectionStringWouldBeSafeHere))
using(OleDbCommand dbcmd = new OleDbCommand(Update, dbConn))
{
dbcmd.Parameters.AddWithValue("#CompanyName", companyName);
dbcmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbcmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbcmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
}
By the way, I hope that your table contains only one record because without a WHERE clause you update every record present with the values of your textboxes.

Related

Eliminating an option from a ComboBox (2), based on the input of the first ComboBox (1) c#

I am creating an airline booking system and I have 2 combo boxes. The first is for Departure City and the second is for Arrival City. I want to be able to eliminate the choice in the first combo box from the second, as I don't want the same city to be able to be submitted as both the departure and arrival city. I am querying the city names from a database.
Here is my code:
public partial class main : Form
{
public main()
{
InitializeComponent();
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
//Departure ComboBox
SQLiteConnection conn = new SQLiteConnection(connectionString);
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboDeparture.DataSource = dt;
comboDeparture.ValueMember = "Descriptions";
comboDeparture.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Arrival ComboBox
private void comboDeparture_DisplayMemberChanged(object sender, EventArgs e)
{
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
SQLiteConnection conn = new SQLiteConnection(connectionString);
**String city = comboDeparture.DisplayMember;**
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue.ToString() + "'";
richTextBox1.Text = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue + "'";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboArrival.DataSource = dt;
comboArrival.ValueMember = "Descriptions";
comboArrival.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks :)
It looks like you're handling the DisplayMemberChanged event on comboDeparture, and trying to update the values of comboArrival in that handler. However, DisplayMemberChanged only triggers when the DisplayMember property changes.
DisplayMember only tells the control which property to display on a data bound control. It isn't tied to the index or value selected in the ComboBox. So, the only time the code to populate comboArrival runs is in the constructor when you set comboDepartarture.DisplayMember. Instead, handle either ComboBox.SelectedIndexChanged or ComboBox.SelectedValueChanged and set the items of comboArrival.
A few other important things to note about your code.
First, you should use a parameterized query when running Sql Statements, rather than concatenating strings. Concatenating strings as you're doing opens you up to SQL Injection Attacks. I'm not familiar with SqlLite and can't provide you with an example of how to modify your code, but perhaps this question can help.
Second, you don't need to re-run the query every time you change the selected value in comboDeparture. Just add comboArrival's data source as a field on the Form and you can filter it. For example...
public partial class main : Form
{
// Your constructors...
private void comboDepartures_SelectedIndexChanged(object sender, EventArgs e)
{
if (_arrivalsDataSource == null)
{
_arrivalsDataSource = new System.Data.DataTable();
// Load _arrivalsDataSource from the database, basically how you're doing it now.
comboArrival.DataSource = _arrivalsDataSource.DefaultView;
comboArrival.DisplayMember = "Descriptions"
comboArribal.ValueMember = "Descriptions"
}
if (comboDeparture.SelectedIndex == -1)
{
_arrivalsDataSource.DefaultView.RowFilter = null; // Clear the filter.
}
else
{
// Set the filter.
_arrivalsDataSource.DefaultView.RowFilter = $"Description <> '{comboDeparture.SelectedValue}'";
}
}
private System.Data.DataTable _arrivalsDataSource = null;
}

Combobox not filling from database C#

I'm trying to fill a combo box on from load from a database, I'm getting the error "Invalid object name 'POOL'"
Form load event to populate dropdown on form load
private void FRMAddTeam_Load(object sender, EventArgs e)
{
if (CMBBXPool.Items.Count > 0)
CMBBXPool.Items.Clear();
Database.CLSDB DatabaseClass = new Database.CLSDB();
DatabaseClass.FillDropDownList();
}
This is the code in my database connection class
public void FillDropDownList()
{
string PoolName = "";
Team.FRMAddTeam TeamAdd = new Team.FRMAddTeam();
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
Code to add the pool name
public void addPoolItem(string PoolName)
{
CMBBXPool.Items.Add(PoolName);
}
Any help is much appreciated
Your code needs to be:
public void FillDropDownList(Team.FRMAddTeam TeamAdd)
{
string PoolName = "";
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
You call it from your form like this:
DatabaseClass.FillDropDownList(this);
This will work, however it is strongly advised to change the implementation of your database class and remove tight coupling with GUI.
It is WRONG to fill your GUI from database class - instead of that, you should return data from your database class and bind your data to GUI in the GUI class.
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Object_orgy
http://en.wikipedia.org/wiki/Separation_of_concerns
Sounds like you dont have table Pool.Are you sure its there?
Log into your SQL management studio and use query analyzer to run the same command.
There could be many reasons for that If your schema is different or do you have permission to access that table ? or are you checking the right database ?
UPDATE:
You should try using SELECT [Name] FROM dbo.TBL_Pool

How to autofill a radio_button, a few combo_boxes, many text_boxes, and a calendar FROM a combo_box selection

I am creating a tool that will allow a Human Resource employee to input various information about a new employee into an access database(for academic purposes). So far I have the layout set-up (as you will be able to see shortly), validation is in a place, and a dataGridView gets populated by using an Access Database I created. Then I have 3 buttons, Submit (Insert), Update and Delete.
PS: I know that the table I am trying to update is huge, but that's what our team decided to do.
Image of my layout:
Human Resource employee tool
The submit and delete works, BUT the update only works if all of the fields are filled with data. The code I wrote tries to update all the fields WHERE the EMPLOYEE_ID equals the value that's selected on the combo_box, so if I try to update only one field I get an error saying "No value given for one or more required parameters". I think that by auto-filling all the field on the left when a value from a combo_box is selected will fix my problem. The thing is that I have no idea on how to accomplish this. Any help would be appreciate it!!
UPDATE STATEMENT.
private void cmdModify_Click(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "UPDATE Employee SET FIRST_NAME = #FirstName , LAST_NAME= #LastName, MIDDLE_NAME = #MiddleName, DATE_HIRED =#DateHired, WAGE_TYPE =#WageType, WAGE = #Wage, GENDER =#Gender, MARTIAL_STATUS =#MartialStatus, UNIT_NUMBER =#UnitNumber, STREET_NUMBER =#StreetNumber, STREET_NAME =#StreetName, CITY =#City, PROVINCE =#Province, POSTAL_CODE =#PostalCode, HOME_NUMBER =#HomeNumber, CELL_NUMBER =#CellNumber, JOB_TITTLE =#JobTittle, END_DATE=7/24/2013, DPT_NAME =#Department, NOTES =#Notes WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
INSERT STATEMENT.
private void Insert_Data()
{
string connectionString = GetConnectionString();
string SqlString = "INSERT INTO Employee (FIRST_NAME, LAST_NAME, MIDDLE_NAME, DATE_HIRED, WAGE_TYPE, WAGE, GENDER, MARTIAL_STATUS,UNIT_NUMBER, STREET_NUMBER, STREET_NAME, CITY ,PROVINCE, POSTAL_CODE, HOME_NUMBER, CELL_NUMBER, JOB_TITTLE, END_DATE, DPT_NAME, NOTES) VALUES (#FirstName,#LastName,#MiddleName,#DateHired,#WageType,#Wage,#Gender,#MartialStatus,#UnitNumber,#StreetNumber,#StreetName,#City,#Province,#PostalCode,#HomeNumber,#CellNumber,#JobTittle,7/24/2013,#Department,#Notes)";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender",rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
DELETE STATEMENT
private void cmdDelete_Click_1(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "DELETE * FROM Employee WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID ";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was deleted from the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
You are getting this error because the AddWithValue method is adding null to the Parameters collection. What you need is for it to add DBNull instead.
cmd.Parameters.AddWithValue("FirstName", txtFname.Text ?? DBNull.Value);
Those SelectedItem values might cause you problems too if they are complex types:
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
You might have to specify a property on the instance to make it work
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem.MyIdProperty);

Use ContentEditable to Save Into DB With ASP.NET?

I'm trying to create a web page where a user can edit the text and when they are done, they hit save and the new text entered is saved into the database.
I'm not getting any errors in my code, but for some reason, the old text is just being rewritten into the db instead of the new text.
Here is my code-behind:
protected void saveBtn_Click(object sender, EventArgs e)
{
string newName;
string newIntro;
string newEduc;
string newWork;
h1New.Text = h1.Text;
newName = h1New.Text;
newIntro = intro.Text;
newEduc = educ.Text;
newWork = employ.Text;
string connectionInfo = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionInfo))
{
connection.Open();
SqlCommand myCommand = new SqlCommand("UPDATE simpleContent SET userName = #newName, infoContent = #newIntro, educContent = #newEduc, workContent = #newWork WHERE userID = #userName", connection);
try
{
string username = HttpContext.Current.User.Identity.Name;
myCommand.Parameters.AddWithValue("#userName", username.ToString());
myCommand.Parameters.AddWithValue("#newName", newName.ToString());
myCommand.Parameters.AddWithValue("#newIntro", newIntro.ToString());
myCommand.Parameters.AddWithValue("#newEduc", newEduc.ToString());
myCommand.Parameters.AddWithValue("#newWork", newWork.ToString());
myCommand.ExecuteNonQuery();
connection.Close();
}
catch
{
Response.Redirect("http://www.google.co.uk");
}
}
}
I would appreciate any pointers that you may have.
try to put you code in format:
protected void saveBtn_Click(object sender, EventArgs e)
{
// add variables
string connectionInfo = (...)
string commandText = (...)
using (...){
SqlCommand myCommand = (...)
// add parameters
try
{
connection.Open();
myCommand.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
(...)
}
}

get the protein that contains specific sequence using OLEDB

Here is a background on my program: each protein is made from a sequence of amino acids(or AA)
I have some tables :tblProInfo(that contains general info about proteins),tblOrderAA(that contains the sequence(AA sequence) of specific protein(for each protein there is a serial number that i set before))
now, I'm trying to retvive the science names of the protein that contains part of sequence that the user put in textbox1. It is likely that more than one protein contains the sequence that the user typed.
Here is my code. I got "Syntax error" and I'm sure I have more mistakes.Please HELP me!
public void OpenDB()
{
dataConnection = new OleDbConnection();
try
{
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
}
catch (Exception e)
{
MessageBox.Show("Error accessing the database: " +
e.Message,
"Errors",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private string FromCodonsToProtein(string codons)
{
OpenDB();
int sizePro=0, i,counter=0,serialPro;
string st="",tempst="";
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT tblProInfo.proInfoAAnum, tblProInfo.proInfoSerialNum,tblProInfo.proInfoScienceName FROM tblProInfo";
OleDbDataReader dataReader = datacommand.ExecuteReader();
while(dataReader.Read())
{
sizePro = dataReader.GetInt32(counter);
serialPro= dataReader.GetInt32(counter+1);
counter++;
OleDbCommand cmd= new OleDbCommand();
cmd.Connection = dataConnection;
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
OleDbDataReader rdr = cmd.ExecuteReader();
tempst="";
for (i = 0; i > sizePro; i++)
{
tempst = tempst + rdr.GetString(i);
}
if (tempst.Contains(codons))
{
st = st + " \n" + dataReader.GetString(counter);
}
}
return st;
}
Missing a space here
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+"WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
rewrite in this way
cmd.CommandText = "SELECT tblOrderAA.orderAACodon1 FROM tblOrderAA"
+" WHERE (((tblOrderAA.orderAASerialPro)='"+serialPro+"'))";
// ^ here
However you should use parametrized query (also with msaccess) to avoid possible errors and injection attacks.
Another problem is the global dataConnection. Don't do that, you gain nothing in this way.
Return the connection and encapsulate it with a using statement.
For example:
public OleDbConnection OpenDB()
{
dataConnection = new OleDbConnection();
dataConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
dataConnection.Open();
return dataConnection;
}
then in the calling code use this syntax
using(OleDbConnection cnn = OpenDB())
{
// in the rest of your code, replace dataConnection with cnn
// The using statement will ensure that in the case of exceptions
// your connection will be allways closed and properly disposed
........
}
EDIT: Can't give you a full working solutions, too many aspects of your problem are unknown to me, however a great simplification will be to change your query in this way
SELECT DISTINCT
tblProInfo.proInfoAAnum,
tblProInfo.proInfoSerialNum,
tblProInfo.proInfoScienceName
FROM tblProInfo LEFT JOIN tblOrderAA
ON tblOrderAA.orderAASerialPro = tblProInfo.proInfoSerialNum
WHERE tblOrderAA.orderAACodon1 = #codons
Try it directly in access using its query editor, if it works as you expected then change your code. You don't need two query and crossed loops to get the results.

Categories

Resources