this doesn't update in my database table. Have I over-looked something?
The values are in the textboxes fine. No errors show, weird.
using (SqlConnection connection = new SqlConnection(#"Data Source = UKMAN1NB10038\SQLEXPRESS; Initial Catalog = TheVets; Integrated Security = True"))
{
SqlCommand command = new SqlCommand("UPDATE OwnerTable SET Owner_Fname =#OwnerFname , Owner_Lname = #OwnerLname, Owner_HouseNo = #OwnerHouse, Owner_Street = #OwnerStreet, Owner_County = #OwnerCounty, Owner_PostCode = #OwnerPost, Owner_Tele = #OwnerTele, Owner_Email = #OwnerEmail WHERE Owner_ID = '" + CB_EDIT_OWNER.SelectedText + "'", connection);
command.CommandType = CommandType.Text;
command.Connection = connection;
command.Parameters.AddWithValue("#OwnerFname", TXT_EDIT_FNAME.Text);
command.Parameters.AddWithValue("#OwnerLname", TXT_EDIT_LNAME.Text);
command.Parameters.AddWithValue("#OwnerHouse", TXT_EDIT_HOUSE.Text);
command.Parameters.AddWithValue("#OwnerStreet", TXT_EDIT_STREET.Text);
command.Parameters.AddWithValue("#OwnerCounty", TXT_EDIT_COUNTY.Text);
command.Parameters.AddWithValue("#OwnerPost", TXT_EDIT_POSTCODE.Text);
command.Parameters.AddWithValue("#OwnerTele", TXT_EDIT_TELE.Text);
command.Parameters.AddWithValue("#OwnerEmail", TXT_EDIT_EMAIL.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
You need to use SelectedItem not SelectedText on the combobox
Replace CB_EDIT_OWNER.SelectedText with:
CB_EDIT_OWNER.SelectedItem
Then this should work.
Related
I've got the following code:
private void btnAddMatter_Click(object sender, EventArgs e)
{
MatterCode = "";
EntityID = 0;
FeeEarnerID = 0;
OpenedByUserID = 0;
CompanyContactDetailsID = 0;
Description = "";
OurReference = "";
TheirReference = "";
DateOpened = DateTime.Now;
MatterTypeID = 0;
DepartmentID = 0;
ResponsibleUserID = 0;
TrustBankAccountID = 0;
BusinessBankAccountID = 0;
string connectionString = "Data Source=***\\SQLEXPRESS;Initial Catalog=STUPELG;Persist Security Info=True;User ID=***;Password=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Matter ( MatterCode, EntityID, FeeEarnerID, OpenedByUserID, CompanyContactDetailsID, Description," +
" OurReference, TheirReference, DateOpened, MatterTypeID, DepartmentID, ResponsibleUserID, TrustBankAccountID, BusinessBankAccountID)" +
" VALUES ( #MatterCode, #EntityID, #FeeEarnerID, #OpenedByUserID, #CompanyContactDetailsID, #Description," +
" #OurReference, #TheirReference, #DateOpened, #MatterTypeID, #DepartmentID, #ResponsibleUserID, #TrustBankAccountID, #BusinessBankAccountID);" +
" SELECT SCOPE_IDENTITY();");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterID", MatterID);
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
cmd.Parameters.AddWithValue("#EntityID", EntityID);
cmd.Parameters.AddWithValue("#FeeEarnerID", FeeEarnerID);
cmd.Parameters.AddWithValue("#OpenedByUserID", OpenedByUserID);
cmd.Parameters.AddWithValue("#CompanyContactDetailsID", CompanyContactDetailsID);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#OurReference", OurReference);
cmd.Parameters.AddWithValue("#TheirReference", TheirReference);
cmd.Parameters.AddWithValue("#MatterTypeID", MatterTypeID);
cmd.Parameters.AddWithValue("#DepartmentID", DepartmentID);
cmd.Parameters.AddWithValue("#ResponsibleUserID", ResponsibleUserID);
cmd.Parameters.AddWithValue("#TrustBankAccountID", TrustBankAccountID);
cmd.Parameters.AddWithValue("#BusinessBankAccountID", BusinessBankAccountID);
cmd.Parameters.AddWithValue("#DateOpened", DateOpened);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UPDATE Matter SET MatterCode = #MatterCode WHERE MatterID = " + MatterCode);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
connection.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Matter " + MatterCode + " successfully created");
}
After the row is inserted, the new MatterID (primary key that is generated automatically) should be copied to the MatterCode field. Currently it works EXCEPT that there is an extra row that is generated at when the button is clicked:
How do I fix this???
Well - this is because your code is executing the INSERT query twice......
connection.Open();
cmd.ExecuteNonQuery(); // first execution
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID); // second execution
I'm not entirely sure what you wanted to do with that SqlDataAdapter - but it's using the same SqlCommand from before, with the INSERT statement, which gets executed a second time......
You can replace this:
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
with
MatterCode = cmd.ExecuteScalar().ToString();
as ExecuteScalar runs the command and returns the value of the first column of the first row of the first resultset.
I'm trying to get values out of my database into my Listbox, I currently send all my results into a new object called Results
I want my listbox to show something like this:
Title(1)(enter)
Url(1)(enter)
Title(2)(enter)
Url(2)(enter)
and so on
It currently still gives an error at OleDbDataReader reader = command.ExecuteReader(); but I have no idea why.
This is the exact code
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = connection;
cmd1.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(lbzoektermen.SelectedItem) + "';";
OleDbDataReader reader1 = cmd1.ExecuteReader();
if(reader1.Read())
{
resultaatid = Convert.ToInt32(reader1["ZoekcriteriaID"]);
}
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekriteriaID = '"+ resultaatid +"';";
OleDbDataReader reader = command.ExecuteReader();
lbresultaten.Items.Clear();
List<Results> resultaten = new List<Results>();
while(reader.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader["Webadress"]);
result.titel = Convert.ToString(reader["Webadress"]);
resultaten.Add(result);
}
foreach(Results result in resultaten )
{
lbresultaten.Items.Add(result.titel);
lbresultaten.Items.Add(result.url);
}
I hope someone could help me,
Kind Regards,
Martijn
Your problem probably lays in your where clause:
SELECT ZoekcriteriaID from Zoekcriteria WHERE **ZoekCriteria**
It should be a column name, not a table name.
I've been trawling through pages and pages on the internet for days now trying different approaches and I'm still not sure how I should be doing this.
On my third InsertCommand, I'd like to reference a column on the other 2 tables.
// Populate a DataSet from multiple Tables... Works fine
sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand("SELECT * FROM hardware", sqlConn);
sqlDA.Fill(ds, "Hardware");
sqlDA.SelectCommand.CommandText = "SELECT * FROM software";
sqlDA.Fill(ds, "Software");
sqlDA.SelectCommand.CommandText = "SELECT * FROM join_hardware_software";
sqlDA.Fill(ds, "HS Join");
// After DataSet has been changed, perform an Insert on relevant tables...
updatedDs = ds.GetChanges();
SqlCommand DAInsertCommand = new SqlCommand();
DAInsertCommand.CommandText = "INSERT INTO hardware (host, model, serial) VALUES (#host, #model, #serial)";
DAInsertCommand.Parameters.AddWithValue("#host", null).SourceColumn = "host";
DAInsertCommand.Parameters.AddWithValue("#model", null).SourceColumn = "model";
DAInsertCommand.Parameters.AddWithValue("#serial", null).SourceColumn = "serial";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Hardware"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO software (description) VALUES (#software)";
DAInsertCommand.Parameters.AddWithValue("#software", null).SourceColumn = "description";
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "Software"); // Works Fine
DAInsertCommand.Parameters.Clear(); // Clear parameters set above
DAInsertCommand.CommandText = "INSERT INTO join_hardware_software (hardware_id, software_id) VALUES (#hardware_id, #software_id)";
// *****
DAInsertCommand.Parameters.AddWithValue("#hardware_id", null).SourceColumn = "?"; // I want to set this to be set to my 'hardware' table to the 'id' column.
DAInsertCommand.Parameters.AddWithValue("#software_id", null).SourceColumn = "?"; // I want to set this to be set to my 'software' table to the 'id' column.
// *****
sqlDA.InsertCommand = DAInsertCommand;
sqlDA.Update(updatedDs, "HS Join");
Could somebody please tell me where I am going wrong and how I could potentially overcome this? Many thanks! :)
With regards to your comments this seems to be one of those occasions where if you and I were sat next to each other we'd get this sorted but it's a bit tricky.
This is code I've used when working with SqlConnection and SqlCommand. There might be stuff here that would help you.
public static void RunSqlCommandText(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
}
public static int RunSqlAndReturnId(string connectionString, string commandText) {
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand comm = conn.CreateCommand();
int id = -1;
try {
comm.CommandType = CommandType.Text;
comm.CommandText = commandText;
comm.Connection = conn;
conn.Open();
var returnvalue = comm.ExecuteScalar();
if (returnvalue != null) {
id = (int)returnvalue;
}
} catch (Exception ex) {
System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
el.Source = "data access class";
el.WriteEntry(ex.Message + ex.StackTrace + " SQL '" + commandText + "'");
} finally {
conn.Close();
comm.Dispose();
}
return id;
}
I'm trying to update a database from my program in C#.
Here is my code which connects to the database and the attempts to update the date column in my RoomsTable table. It looks good to me but nothing happens in the database.
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked='9/27/2012'";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();
I don't know why it isn't working. It looks to me like everything is there.
use OleDBCommand
string updateCommand = "UPDATE RoomsTable SET [Date Checked]='9/27/2012'";
updateCommand = new OleDbCommand(updateCommand, updateConnection);
updateCommand.ExecuteNonQuery();
updateConnection.Close();
maybe you could refractor the code using Using statement and parameterized the query. and column name Date Checked should be escaped with brackets.
string updateCommand = "UPDATE RoomsTable SET [Date Checked]=#checkedDate WHERE ID = #id"; // '9/27/2012'
using (OleDbConnection conn = new OleDbConnection("connectionStringHERE"))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = updateCommand;
comm.CommandType = CommandType.Text
comm.Parameters.AddWithValue("#checkedDate", this.dateTimePicker1.Value)
comm.Parameters.AddWithValue("#id", row.roomID);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
you have to write this:
updateConnection = new System.Data.OleDb.OleDbConnection();
updateConnection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb";
updateConnection.Open();
MessageBox.Show("Connected");
string updateCommand = "UPDATE RoomsTable SET Date Checked= '"+9/27/2012+"' ";
updateAdapter = new OleDbDataAdapter(updateCommand, updateConnection);
updateConnection.Close();
updateConnection.Dispose();
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.