save checkbox value in access database with vb.net 2010 (wpf c#) - c#

guy how can i insert the value of checkbox in access database or any database.
i tried any of this sql statement but it still give me error: OleDbException was Unhandled. Data type mismatch in criteria expression. and it's pointing to myData = myCommand.ExecuteReader();
note that allowviewpsr is a boolean type of field in ms access database or the one with YES/NO. :) chkviewpsr is mycheckbox
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and here's my connector:
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.SelectCommand = myCommand;
myData = myCommand.ExecuteReader();
EDITED:
hi anandkumar thanks for the quick replay i tried NonQuery but it gives same error as above
SQL = "UPDATE `RWMUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Snapshot of my Access Database :(

Instead of
myAdapter.SelectCommand = myCommand;
myCommand.ExecuteReader();
Use
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Reference:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx

Related

No errors in the code, but no changes occur in the table when trying to update it

I'm trying to update my data in C# Win Form.
I created a button "update", but whenever I run it, I don't see any changes in the table and any occurring errors
void insertdata() {
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM airport";
adapter.SelectCommand = cmd;
table.Clear();
adapter.Fill(table);
dgv.DataSource = table;
}
private void button_update_Click(object sender, EventArgs e)
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE airport SET p_name = '"+textBox2.Text+ "',p_age = '" + textBox3.Text + "', c_name = '" + textBox4.Text + "', date = '" + textBox5.Text + "', city_t = '" + textBox6.Text + "', city_f ='" + textBox7.Text + "', trip_num = '" + textBox8.Text + "', plane_type = '" + textBox9.Text+"' WHERE p_id = '"+textBox1+"'";
cmd.ExecuteNonQuery();
insertdata();
}
I've tried to add
connection.Open();
connection.Close();
However, I keep getting: "System.InvalidOperationException: "The connection was not closed. The connection is open."
Could there be any change in my code for updating the rows in the table, as whenever I run it I don't get any errors.
Please note the you wrote
WHERE p_id = '"+textBox1+"'
Instead of
WHERE p_id = '"+textBox1.Text+"'
Probably you don't have an ID that equals to the textBox...

WHERE Columnname from comboBox = value?

Iam trying to figure out a way to select a value on a comboBox which would then be used for and mysql command.
Iam new to coding in c# so i got know clue where my mistake should be.. searched some hours now and found nothing.
It is supposed to be used as an filter to search through a huge stack of customers data to for example only show customers living in Berlin, oder working as...
if (checkBoxrecruitingsearch2.Checked)
{
MySqlCommand cmddtschichten = conn.CreateCommand();
cmddtschichten.CommandType = CommandType.Text;
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE '"+ comboBoxrecruitingfilter.Text +"' = '" + textBoxrecruitingsearch.Text + "' and '" + comboBoxrecruitingsearch2.Text + "' = '" + textBoxrecruitingsearch2.Text + "'";
cmddtschichten.ExecuteNonQuery();
DataTable dtschichten = new DataTable();
MySqlDataAdapter cmddaschichten = new MySqlDataAdapter(cmddtschichten);
cmddaschichten.Fill(dtschichten);
dtschichten.Columns["id"].ColumnName = "Bewerber ID";
dtschichten.Columns["Wohnort"].ColumnName = "Wohnort";
dtschichten.Columns["Berufsbezeichnung"].ColumnName = "Berufsbezeichnung";
BindingSource bSourceschichten = new BindingSource();
bSourceschichten.DataSource = dtschichten;
dataGridViewrecruitingsearchresult.DataSource = bSourceschichten;
cmddaschichten.Update(dtschichten);
}
else
{
MySqlCommand cmddtschichten = conn.CreateCommand();
cmddtschichten.CommandType = CommandType.Text;
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE '"+ comboBoxrecruitingfilter.Text +"' = '" + textBoxrecruitingsearch.Text + "'";
cmddtschichten.ExecuteNonQuery();
DataTable dtschichten = new DataTable();
MySqlDataAdapter cmddaschichten = new MySqlDataAdapter(cmddtschichten);
cmddaschichten.Fill(dtschichten);
dtschichten.Columns["id"].ColumnName = "Bewerber ID";
dtschichten.Columns["Wohnort"].ColumnName = "Wohnort";
dtschichten.Columns["Berufsbezeichnung"].ColumnName = "Berufsbezeichnung";
BindingSource bSourceschichten = new BindingSource();
bSourceschichten.DataSource = dtschichten;
dataGridViewrecruitingsearchresult.DataSource = bSourceschichten;
cmddaschichten.Update(dtschichten);
}
the expected result would be to get back all "bewerber" where column (choosen on comboBoxrecruitingfilter) equals textBoxrecuitingsearch
I do get shown a list with all entry's when executing with empty text and combobox, otherwise it shows nothing
SOLUTION
If I remember correctly mysql does have a specific column name delimiter " ` " but in your where you are using " ' ". Very similar but different characters
WHERE ' "+ comboBoxrecruitingfilter.Text +" ' = '" + textBoxrecruitingsearch.Text + " '
should be:
WHERE ` "+ comboBoxrecruitingfilter.Text +" ` = '" + textBoxrecruitingsearch.Text + " '
As a side note, your code is subject to SQL Injection, if your users are not trusted you have a security problem/could be hacked. Should move to parametrized queries instead.
Remove the ' around the field name in the where clause:
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE "+ comboBoxrecruitingfilter.Text +" = '" + textBoxrecruitingsearch.Text + "' and " + comboBoxrecruitingsearch2.Text + " = '" + textBoxrecruitingsearch2.Text + "'";
and
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE "+ comboBoxrecruitingfilter.Text +" = '" + textBoxrecruitingsearch.Text + "'";
If you have space between your field names, you can use one of the following:
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE `"+ comboBoxrecruitingfilter.Text +"` = '" + textBoxrecruitingsearch.Text + "'";
or
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE ["+ comboBoxrecruitingfilter.Text +"] = '" + textBoxrecruitingsearch.Text + "'";

Cannot Find Table 0 from other form

Tried to move data from one form to another and there is a problem with the table. Yes I found such themes with a mistake, and tried to correct himself, but something went wrong.
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
You are expecting results to be returned from your query, but what you do is just INSERT statement.
For inserting values you should use ExecuteNonQuery method of SqlCommand (see this for reference).
Then, assign another command: SELECT to get the results, then you can fill DataSet with the result and then you can fill DataGridView with it.
Also: you are rpone to SQL injection, use parametrized query to prevent yourself from such threat (see this for reference).

How to update data in datagridview?

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET (Supplier, InvoiceNumber, DRNumber, PONumber, ItemQty, ReceivedDate, Address, Contact, ReceivedBy, AssetNumber) (Supplier ='" + this.supplierTextBox.Text + "',InvoiceNumber ='" + this.invoiceNumberTextBox.Text + "',DRNumber ='" + this.dRNumberTextBox.Text + "',PONumber ='" + this.pONumberTextBox.Text + "',ItemQty ='" + this.itemQtyTextBox.Text + "',ReceivedDate ='" + this.receivedDateDateTimePicker.Text + "',Address ='" + this.addressTextBox.Text + "',Contact ='" + this.contactTextBox.Text + "',ReceivedBy ='" + this.receivedByTextBox.Text + "',AssetNumber ='" + this.assetNumberTextBox.Text + "'", conn);
cmd.CommandType = CommandType.Text;
OdbcDataAdapter ds = new OdbcDataAdapter(cmd);
ds.SelectCommand = cmd;
System.Data.DataTable dtable = new System.Data.DataTable();
ds.Fill(dtable);
tbl_deliveryDataGridView.DataSource = dtable;
conn.Open();
cmd.ExecuteNonQuery();
update button won't work, please check if my update statement is correct. i am using c#..............
I think your Query is incorrect.
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET Supplier ='" + this.supplierTextBox.Text + "',InvoiceNumber ='" + this.invoiceNumberTextBox.Text + "',DRNumber ='" + this.dRNumberTextBox.Text + "',PONumber ='" + this.pONumberTextBox.Text + "',ItemQty ='" + this.itemQtyTextBox.Text + "',ReceivedDate ='" + this.receivedDateDateTimePicker.Text + "',Address ='" + this.addressTextBox.Text + "',Contact ='" + this.contactTextBox.Text + "',ReceivedBy ='" + this.receivedByTextBox.Text + "',AssetNumber ='" + this.assetNumberTextBox.Text + "'", conn);
Then where is your Where clause? just add it on the query
Then
cmd.ExecuteNonQuery();
ds= newodbcDataAdapter(cmd);
ds.Fill(dtable);
tbl_deliveryDataGridView.ItemsSource = dtable.DefaultView;
You better execute your query first before displaying it to your datagrid for that you'll able to see the updated table.

C# AND ACCESS - Data type mismatch in criteria expression

I've created a code that updates/edits details of a/an computer/electronic product for a C# program connecting to the MS Access. Here are the codes:
OleDbCommand cmd = new OleDbCommand("UPDATE Available SET ProductType = '" + newAvailable.ProductType + "', Brand = '"+ newAvailable.Brand + "', Model = '" + newAvailable.Model + "', SerialNo = '" + newAvailable.SerialNo + "', Remarks = '" + newAvailable.Remarks + "', RAM = '" + newAvailable.RAM + "', HDD = '" + newAvailable.HDD + "', ODD = '" + newAvailable.ODD + "', VideoCard = '" + newAvailable.VideoCard + "', PS = '" + newAvailable.PS + "' WHERE AvailableID = '"+oldAvailable.AvailableID+"'", cnn);
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
AvailableID accepts Int32 values and the rest of the variables are string. The program is executable, yet the C# detected the error.
Data type mismatch in criteria expression.
What should I do?
I suspect that you're not passing one of your parameters correct probably the AvailableID, instead try to add the parameters this way:
var cmd = new OleDbCommand
{
Connection = cnn,
CommandType = CommandType.Text,
CommandText = "UPDATE Available SET ProductType = ?, Brand = ?, Model = ?, SerialNo = ?, Remarks = ?, RAM = ?, ODD = ?, VideoCard = ?, PS = ? WHERE AvailableID = ?"
};
cmd.Parameters.Add(new OleDbParameter {Value = newAvailable.ProductType});
cmd.Parameters.Add(new OleDbParameter {Value = newAvailable.Brand});
// add the other parameters ...
As a side note, it's not a good idea to generate queries by concatenating strings anyway you should always use parameters.
remove (' ') for those has a integer value
Try this
OleDbCommand cmd = new OleDbCommand("UPDATE Available SET ProductType = '" + newAvailable.ProductType + "', Brand = '"+ newAvailable.Brand + "', Model = '" + newAvailable.Model + "', SerialNo = '" + newAvailable.SerialNo + "', Remarks = '" + newAvailable.Remarks + "', RAM = '" + newAvailable.RAM + "', HDD = '" + newAvailable.HDD + "', ODD = '" + newAvailable.ODD + "', VideoCard = '" + newAvailable.VideoCard + "', PS = '" + newAvailable.PS + "' WHERE AvailableID = "+oldAvailable.AvailableID, cnn);
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
simple is to put a debug point on this and check the query. Copy it and run it in access directly and make changes with data. You will find out what parameter value you are entering is wrong.
I would use something like this to achieve what you are trying to do. This code works fine for me with MS Access 2013
//setting up connection.
OleDbConnection conn = new OledbConnection("connectionstring goes here");
//set the command string query
string cmdStr = "UPDATE Available SET ProductType = ?, Brand = ?, Model = ?, SerialNo = ?, Remarks = ?, RAM = ?, ODD = ?, VideoCard = ?, PS = ? WHERE AvailableID = ?";
//create the command
OleDbCommand cmd = new OleDbCommand(cmdStr,conn);
//add parameters
cmd.Parameters.AddWithValue("#p1",newAvailable.Brand);
cmd.Parameters.AddWithValue("#p2",newAvailable.Brand);
cmd.Parameters.AddWithValue("#p3",newAvailable.SerialNo);
// add all your parameters in the correct order here below .

Categories