how to convert value stored in session as an integer - c#

I am trying to save data into my database using the value stored in a session, however, the value must be of type int as stated in the database. how do I go about doing this? the code for the insertion is below.
protected void btnSave_outcome_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand sqlCmd = new SqlCommand("OutcomeCreateOrUpdate", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#outcomeID", (hfoutcomeID.Value == "" ? 0 : Convert.ToInt32(hfoutcomeID.Value)));
sqlCmd.Parameters.AddWithValue("#learning_activity", (ddlActivity.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
sqlCmd.Parameters.AddWithValue("#audience", (txtAudience1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#condition", (txtCondition1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#bloom_level", (ddlCategory1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#verb", (ddlVerb1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#product", (txtProduct2.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#degree", (txtDegree1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#statement", ("Given " + txtCondition1.Text.Trim() + ", " + txtAudience1.Text.Trim() + " Will be able to " + ddlVerb1.SelectedItem.Text + " " + txtProduct2.Text.Trim()+ " " + txtDegree1.Text.Trim() +"."));
//sqlCmd.Parameters.AddWithValue("#moduleID", (ddlmodules.SelectedIndex));
sqlCmd.ExecuteNonQuery();
con.Close();
//string objectiveID = hfobjectiveID.Value;
string outcomeID = hfoutcomeID.Value;
Clear();
if (outcomeID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
//FillGridView(); for outcomes
new_outcome.Visible = true;
}
and I created the session as follows
protected void redirect_outcomes_Click(object sender, EventArgs e)
{
Session["objectiveID"] = objectiveID.ToString();
//Session["module"] = ddlmodules.SelectedValue;
//Response.Redirect("learningoutcomes.aspx?MultiView1.ActiveIndex=" +2);
final_objective1.Text = "Given " + txtCondition.Text.Trim() + ", " + txtAudience.Text.Trim() + " Will be able to " + txtVerb.Text.Trim() + " " + txtProduct.Text.Trim() + " .";
MultiView1.Visible = false;
GoToAudience1.Visible = false;
MultiView2.ActiveViewIndex = 0;
}

Your code:-
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
My suggestion:-
if(Session["objectiveID"] != null)
{
sqlCmd.Parameters.AddWithValue("#objectiveID", Convert.ToInt32(Session["objectiveID"]));
}
No need to use try parse/parse because you are storing only integer value in session. So session have either empty or integer value.

Related

Autocomplete comboBox that checks items in its list are entered

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
}
}

CheckBox Not Sending Checked Value to Access Database C# Asp

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

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

Error Creating DataBase name

I am trying to create a database here, I am able to create it with just a single word like "test" or "example". However, when i tried to create a database name, 2 words with a spacing in the middle for example "testing table" , it does not create the database. I tried [],'' and {} but it did not worked. Here is my code.
str = "CREATE DATABASE "+textBox1.Text+" ON PRIMARY " +
"(NAME = "+textBox1.Text+"_Data, " +
"FILENAME = 'C:\\"+textBox1.Text+".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = "+textBox1.Text"+_Log, " +
"FILENAME = 'C:\\"+textBox1.Text"+.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
From this article Create a SQL Server database using C#, you could try sanitizing your input, for example:
private void button2_Click(object sender, System.EventArgs e)
{
DatabaseParam DBParam = new DatabaseParam();
DBParam.DatabaseName = textBox1.Text;
//Assign Data file parameters
DBParam.DataFileGrowth = "10%";
DBParam.DataFileName = textBox3.Text;
DBParam.DataFileSize = "2";//2MB at the init state
DBParam.DataPathName = textBox2.Text;
//Assign Log file parameters
DBParam.LogFileGrowth = "10%";
DBParam.LogFileName = textBox10.Text;
DBParam.LogFileSize = "1";//1MB at the init state
DBParam.LogPathName = textBox11.Text;
CreateDatabase(DBParam);
}
private void CreateDatabase(DatabaseParam DBParam)
{
System.Data.SqlClient.SqlConnection tmpConn;
string sqlCreateDBQuery;
tmpConn = new SqlConnection();
tmpConn.ConnectionString = "SERVER = " + DBParam.ServerName + "; DATABASE = master; User ID = sa; Pwd = sa";
sqlCreateDBQuery = " CREATE DATABASE " + DBParam.DatabaseName + " ON PRIMARY "
+ " (NAME = " + DBParam.DataFileName +", "
+ " FILENAME = '" + DBParam.DataPathName +"', "
+ " SIZE = 2MB,"
+ " FILEGROWTH =" + DBParam.DataFileGrowth +") "
+ " LOG ON (NAME =" + DBParam.LogFileName +", "
+ " FILENAME = '" + DBParam.LogPathName + "', "
+ " SIZE = 1MB, "
+ " FILEGROWTH =" + DBParam.LogFileGrowth +") ";
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
MessageBox.Show(sqlCreateDBQuery);
myCommand.ExecuteNonQuery();
MessageBox.Show("Database has been created successfully!", "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Create Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
tmpConn.Close();
}
return;
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
textBox3.Text = textBox1.Text + "_Data";
textBox10.Text = textBox1.Text + "_Log";
}

EMPLOYEE MDB ACCESS GET ERROR 'Message: No value given for one or more required parameters'

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string gs_ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=YorkProducts.accdb;"
+ "Persist Security Info=False;";
public Form1()
{
InitializeComponent();
}
private void ClearForm()
{
tb_EmpNr.Clear();
tb_LastName.Clear();
tb_FirstName.Clear();
tb_MiddleName.Clear();
tb_Address.Clear();
tb_Zip.Clear();
tb_City.Clear();
tb_State.Clear();
tb_Phone.Clear();
tb_PayLevel.Clear();
tb_PayGrade.Clear();
tb_DOH.Clear();
}//end clear form
private void GetCityState()
{
try
{
//create the connection
string Query = "SELECT City, State " +
" FROM tbl_Zip WHERE Zip=" + "\"" + tb_Zip.Text + "\"" + "";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Read();
tb_City.Text = Reader.GetString(0);
tb_State.Text = Reader.GetString(1);
Reader.Close();
Connection.Close();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS GET ZIP ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end get city state
private void GetRecFromDatabase(string s_EmpNr)
{
try
{
//create the connection
string Query = "SELECT EmpNumber, EmpLastName, EmpFirstName, EmpMiddleName, EmpAddress, EmpZip," +
" EmpPhone, EmpPayLevel, EmpPayGrade, EmpHireDate" +
" FROM tbl_Employee WHERE EmpNumber=" + "\"" + s_EmpNr + "\"" + "";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Read();
tb_EmpNr.Text = Reader.GetString(0);
tb_LastName.Text = Reader.GetString(1);
tb_FirstName.Text = Reader.GetString(2);
tb_MiddleName.Text = Reader.GetString(3);
tb_Address.Text = Reader.GetString(4);
tb_Zip.Text = Reader.GetString(5);
tb_Phone.Text = Reader.GetString(6);
tb_PayGrade.Text = String.Format("{0}", Reader.GetInt32(7));
tb_PayLevel.Text = String.Format("{0}", Reader.GetInt32(8));
tb_DOH.Text = String.Format("{0:d}", Reader.GetDateTime(9));
Reader.Close();
Connection.Close();
GetCityState();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS GET ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end GetRecFromDatabase
private void b_Clear_Screen_Click_Click(object sender, EventArgs e)
{
ClearForm();
tb_EmpNr.Focus();
}
private void b_Add_Customer_Click(object sender, EventArgs e)
{
try
{
//create the connection
string Query = "INSERT INTO tbl_Employee (EmpNumber, EmpLastName, EmpFirstName, EmpMiddleName, " +
"EmpAddress, EmpZip, EmpPhone, EmpHireDate, EmpPayLevel, EmpPayGrade)" +
"VALUES(" + "\"" + tb_EmpNr.Text + "\"" + ", " //strings get double quotes
+ "\"" + tb_LastName.Text + "\"" + ", "
+ "\"" + tb_FirstName.Text + "\"" + ", "
+ "\"" + tb_MiddleName.Text + "\"" + ", "
+ "\"" + tb_Address.Text + "\"" + ", "
+ "\"" + tb_Zip.Text + "\"" + ", "
+ "\"" + tb_Phone.Text + "\"" + ", "
+ "#" + tb_DOH.Text + "#" + ", "
+ tb_PayLevel.Text + ", "
+ tb_PayGrade.Text
+ ")";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Close();
Connection.Close();
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS ADD ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}
private void b_Get_Customer_Click(object sender, EventArgs e)
{//get a specific rec
GetRecFromDatabase(tb_EmpNr.Text);
}
private void tb_Zip_TextChanged(object sender, EventArgs e)
{//get the city and state
GetCityState();
}
private void b_Get_Next_Customer_Click(object sender, EventArgs e)
{//get next rec
string s_NextRec = Convert.ToString(Convert.ToInt32(tb_EmpNr.Text) + 1);
GetRecFromDatabase(s_NextRec);
}
private void b_Update_Customer_Click(object sender, EventArgs e)
{//update the record
try
{
string Query = "UPDATE tbl_Employee SET " +
"EmpLastName =" + "\"" + tb_LastName.Text + "\"" + ", " +
"EmpFirstName =" + "\"" + tb_FirstName.Text + "\"" + ", " +
"EmpMiddleName =" + "\"" + tb_MiddleName.Text + "\"" + ", " +
"EmpAddress =" + "\"" + tb_Address.Text + "\"" + ", " +
"EmpZip =" + "\"" + tb_Zip.Text + "\"" + ", " +
"EmpPhone =" + "\"" + tb_Phone.Text + "\"" + ", " +
"EmpHireDate =" + "#" + tb_DOH.Text + "#" + " " + ", " +
"EmpPayLevel =" + Convert.ToInt32(tb_PayLevel.Text) + ", " +
"EmpPayGrade =" + Convert.ToInt32(tb_PayGrade.Text) +
" WHERE EmpNumber =" + "\"" + tb_EmpNr.Text + "\"" + " ";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();
Reader.Close();
Connection.Close();
GetRecFromDatabase(tb_EmpNr.Text);
}//end try
catch (Exception error)
{
MessageBox.Show("Message: " + error.Message,
"EMPLOYEE MDB ACCESS ERROR", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}//end catch
}//end update click
}//end class
}//end namespace
This program is supposed to grab data from an access database that I have manually created and place the data into the fields of a form. I have placed the access database into the debug folder of the project(in visual studio) however I am receiving the error message stated in the title. I think it is possible that I have the database file in the wrong location? I have added Microsoft Access 14.0 as a reference and installed the Microsoft Access Database engine for my version of access. Any help would be appreciated! Thanks!
Solution 1:
string Query = "SELECT City, State FROM tbl_Zip WHERE Zip='" + tb_Zip.Text+"'";
Solution 2:
//create the connection
string Query = "SELECT City, State FROM tbl_Zip WHERE Zip=#zip";
OleDbConnection Connection = new OleDbConnection(gs_ConnString);
OleDbCommand Command = new OleDbCommand(Query, Connection);
Command.Parameters.AddWithValue("#zip",tb_Zip.Text);
Connection.Open();
OleDbDataReader Reader;
Reader = Command.ExecuteReader();

Categories

Resources