An OleDbParameter with ParameterName "" is not contained by this OleDbParameterCollection - c#

I keep getting a parameter name error? at the bottom I have attached an image to help explain the problem.
private void loadProgress(string jobNumber)
{
productioninfo.Open();
OleDbCommand _contractReview = new OleDbCommand ("SELECT [Contract Review] FROM [Main$] WHERE [Job No] = '#Job No'", productioninfo);
_contractReview.Parameters.Add("#Job No", OleDbType.Char);
_contractReview.Parameters["Job No"].Value = jobNumber;
OleDbDataReader dr = _contractReview.ExecuteReader();
while (dr.Read())
{
}
dr.Close();
}

Try like this;
OleDbCommand _contractReview = new OleDbCommand ("SELECT [Contract Review] FROM [Main$] WHERE [Job No] = #JobNo", productioninfo);
_contractReview.Parameters.Add("#JobNo", OleDbType.Char);
_contractReview.Parameters["JobNo"].Value = jobNumber;
And don't use spaces in your table and column names. It is not recommended.
Check out Database, Table and Column Naming Conventions?

Related

Insert into mysql tables

I'm trying to insert some records to 2 tables at same event
private void Btngravar_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;database=saude;Password=");
conn.Open();
MySqlCommand objcmd = new MySqlCommand("insert into dispensacao (DESTINATARIO,COD_UNIDADE,COD_DEPARTAMENTO,DATA,SOLICITANTE,DEFERIDO_POR) values(?,?,?,?,?,?)", conn);
objcmd.Parameters.Add("#DESTINATARIO", MySqlDbType.VarChar, 45).Value = Cmbdestinatario.Text;
objcmd.Parameters.AddWithValue("#COD_UNIDADE", string.IsNullOrEmpty(Txtcodigounidade.Text) ? (object)DBNull.Value : Txtcodigounidade.Text);
objcmd.Parameters.AddWithValue("#COD_DEPARTAMENTO", string.IsNullOrEmpty(Txtcodigodep.Text) ? (object)DBNull.Value : Txtcodigodep.Text);
DateTime fdate = DateTime.Parse(Txtdata.Text);
objcmd.Parameters.Add("#DATA", MySqlDbType.DateTime).Value = fdate;
objcmd.Parameters.Add("#SOLICITANTE", MySqlDbType.VarChar, 45).Value = Txtsolicitante.Text;
objcmd.Parameters.Add("#DEFERIDO_POR", MySqlDbType.VarChar, 45).Value = Txtdeferido.Text;
objcmd.ExecuteNonQuery();
conn.Close();
conn.Open();
objcmd = new MySqlCommand("insert into produtos_disp(COD_DISPENSACAO,COD_PRODUTO,PRODUTO,QUANTIDADE) values (?,?,?,?)", conn);
string selectid = "select ifnull (max(ID),1) from dispensacao";
objcmd = new MySqlCommand(selectid, conn);
MySqlDataReader reader = objcmd.ExecuteReader();
if (reader.Read())
{
Txtcodigo.Text = reader.GetString("ID");
}
//Txtcodigo.DataBindings.Add("Text", dtid, "ID");
objcmd.Parameters.AddWithValue("#COD_DISPENSACAO", Txtcodigo.Text);
objcmd.Parameters.AddWithValue("#COD_PRODUTO", dtproddisp.Rows[0][0]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][1]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][2]);
Code from the comment
string selectQuery = "SELECT * from departamento";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbdestinatario.DisplayMember = "nome";
Cmbdestinatario.ValueMember = "CODIGO";
Cmbdestinatario.DataSource = dt2;
Txtcodigodep.DataBindings.Add("Text", dt2, "CODIGO");
The first part is working, I can see records inserted on dispensacao table, but the second isn't working, error:
Could not find specified column in results: ID
and I need to get products from datagridview,
App screen:
MySQL Dispensacao table:
My problem now is inserting those selected products from datagridview on database and get the id from dispensacao to insert on products table,
If you want to insert more rows in a database(from what I known), you should add a checkbox in a DataGridView Column and store checked rows to a list. Then you should use a for loop to insert each data to Database by list values.
If you want the code please comment me.

How to insert a datatable to an access database in C#

I have 2 table in an access database
now I want to select from one table and insert them into another one.
this is my code but it shows an exception in line Cmd.ExecuteNonQuery();
{"Syntax error (missing operator) in query expression 'System.Object[]'."}
the code is :
public static void SetSelectedFeedIntoDB(Form2 frm2)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID=" + frm2.FeedSelectListBox.SelectedValue, Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Connection.Open();
foreach (DataRow DR in DTable.Rows)
{
Cmd.CommandText = "insert into SelectedFeeds Values(" + DR.ItemArray + ")";
Cmd.ExecuteNonQuery();
}
Connection.Close();
}
what should I do to fix this?
Your error is caused by the fact that you are concatenating the ItemArray property of a DataRow to a string. In this case the ItemArray (that is an instance of an object[]) has no method that automatically produces a string from its values and thus returns the class name as a string "object[]" but of course this produces the meaningless sql string
"insert into SelectedFeeds Values(object[])";
But you could simply build a SELECT .... INTO statement that will do everything for you without using DataTables and Adapters
string cmdText = #"SELECT FeedLibrary.* INTO [SelectedFeeds]
FROM FeedLibrary
where ID=#id";
using(OleDbConnection Connection = new OleDbConnection(StrCon))
using(OleDbCommand cmd = new OleDbCommand(cmdText, Connection))
{
Connection.Open();
cmd.Parameters.Add("#id", OleDbType.Integer).Value = Convert.ToInt32( frm2.FeedSelectListBox.SelectedValue);
cmd.ExecuteNonQuery();
}
However, the SELECT ... INTO statement creates the target table but gives error if the target table already exists. To solve this problem we need to discover if the target exists. If it doesn't exist we use the first SELECT ... INTO query, otherwise we use a INSERT INTO ..... SELECT
// First query, this creates the target SelectedFeeds but fail if it exists
string createText = #"SELECT FeedLibrary.* INTO [SelectedFeeds]
FROM FeedLibrary
where ID=#id";
// Second query, it appends to SelectedFeeds but it should exists
string appendText = #"INSERT INTO SelectedFeeds
SELECT * FROM FeedLibrary
WHERE FeedLibrary.ID=#id";
using(OleDbConnection Connection = new OleDbConnection(StrCon))
using(OleDbCommand cmd = new OleDbCommand("", Connection))
{
Connection.Open();
// Get info about the SelectedFeeds table....
var schema = Connection.GetSchema("Tables",
new string[] { null, null, "SelectedFeeds", null});
// Choose which command to execute....
cmd.CommandText = schema.Rows.Count > 0 ? appendText : createText;
// Parameter #id is the same for both queries
cmd.Parameters.Add("#id", OleDbType.Integer).Value = Convert.ToInt32( frm2.FeedSelectListBox.SelectedValue);
cmd.ExecuteNonQuery();
}
Here we have two different queries, the first one create the SelectedFeeds table as before, the second one appends into that table.
To discover if the target table has already been created I call Connection.GetSchema to retrieve a datatable (schema) where there is a row if the table SelectedFeeds exists or no row if there is no such table.
At this point I set the OleDbCommand with the correct statement to execute.

Fill combobox with only 1 kind of data

Assuming that i have the database items:
Hello
Hello
Hello
I just want to display only one "Hello"
Here is my code....
OleDbCommand cmd = new OleDbCommand("Select *from login", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
var value = dr["dtlogin"].ToString();
if (!combo1.Items.Contains(value))
{
combo1.Items.Add(value);
}
Check for the item before adding using Contains
if(!combo1.Items.Contains(dr["dtlogin"].ToString()))
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
If you r looking for distinct value's to be bind to ur combobox then use this.
OleDbCommand cmd = new OleDbCommand("Select distinct * from login", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
combo1.Items.Add(dr["dtlogin"].ToString());
}
You can just use ExecuteScalar to get first column of the first row. Other rows are ignored.
I assume they are string, you can do;
using(OleDbCommand cmd = new OleDbCommand("Select dtlogin from login", con);)
{
string s = (string)cmd.ExecuteScalar();
combo1.Items.Add(s);
}
Also use using statement to dispose your OleDbCommand and con.

How to Display data in textbox using MS Access database

Im trying to display user data from database into textbox, so that user can edit/update that data later.
Im getting error of no value has been set for at least one of the required parameters.
I did not write the SELECT * FROM, because i'm not displaying data like AdminRights.
Can you please help me fix the error?
This is my code
private void refresh_Click(object sender, RoutedEventArgs e)
{
if (!isPostBack)
{
DataTable dt = new DataTable();
con.Open();
OleDbDataReader dr = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Name], [LastName], [UserName], [Password], [Address], [Email] FROM User WHERE [ID] = ?", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
con.Close();
}
}
.....FROM User WHERE [ID] = ?", con);
The ? placeholder requires a parameter defined in the command parameters collection.
So, before calling ExecuteReader you need to add the parameter for the ID field
cmd.Parameters.AddWithValue("#p1", ????value for the ID field);
dr = cmd.ExecuteReader();
If you want to retrieve a single record from your table you need to know the value for the field that uniquely identifies the records in your table.
To get that value it is necessary to understand how do you reach this code. If you select a row from a list, grid or combo, probably you have loaded that control with your user names and their ID.
String id = idTextBox.Text;
OleDbCommand command = new OleDbCommand("Select *from User Where [ID]= "+ id +" ");
command.Connection = conn;
OleDbDataReader dr = null;
conn.Open();
dr = command.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
conn.Close();
this will work fine change lines and execute

Access Database error:: “No value given for one or more required parameters.”

I have a datagridview. In this DGV first colum is a combobox column. I want to make, when this combobox value is selected next fild will be filled automatically from database. But there shows a error.
No value given for one or more required parameters on
OleDbDataReader dr1 = cmd1.ExecuteReader();
I post the code. Please help me.
OleDbConnection con = new OleDbConnection(conn);
con.Open();
for (int i = 0; i < dgv.Rows.Count; i++)
{
string query = "select Description from General where AccCode='" +
dgv.Rows[i].Cells[0].Value +
"' and conpanyID='" +
label1.Text + "'";
OleDbCommand cmd1 = new OleDbCommand(query, con);
//OleDbDataAdapter daBranchName = new OleDbDataAdapter(cmd);
OleDbDataReader dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{
dgv.Rows[i].Cells[1].Value = dr1["Description"].ToString();
}
}
con.Close();
This kind of string concatenations are open for SQL Injection attacks.
Use parameterized queries instead.
string query = "select [Description] from [General] where AccCode= ? and conpanyID= ?";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("#acc", dgv.Rows[i].Cells[0].Value);
cmd1.Parameters.AddWithValue("#ID", label1.Text);
As HansUp pointed, Description and General are reserved keywords. Use them with square brackets like [Description] and [General]
As suggested, use parameterized queries.
As far as the error is concerned, I'm guessing this field name is wrong:
conpanyID=
should be:
companyID=
Use Parameters, otherwise it will open for sql injection attacks.
string query = "select [Description] from General where AccCode=? and conpanyID=?";
now you can set parameters
cmd.Parameters.AddWithValue("#p1", val1);
cmd.Parameters.AddWithValue("#p2", val2);

Categories