I am having issues updating a selected row on a datagridview that pulls from a database in another form.
I used this to get the information from the datagridview into the textboxes on the other form:
private void updateAppointmentButton_Click(object sender, EventArgs e)
{
UpdateAppointment updateAppointment = new UpdateAppointment();
updateAppointment.mainFormObject = this;
updateAppointment.customerIdBox.Text = appointmentCalendar.CurrentRow.Cells[0].Value.ToString();
updateAppointment.customerNameBox.Text = appointmentCalendar.CurrentRow.Cells[1].Value.ToString();
updateAppointment.typeBox.Text = appointmentCalendar.CurrentRow.Cells[2].Value.ToString();
updateAppointment.startTimeBox.Value = Convert.ToDateTime(appointmentCalendar.CurrentRow.Cells[4].Value.ToString());
updateAppointment.endTimeBox.Value = Convert.ToDateTime(appointmentCalendar.CurrentRow.Cells[3].Value.ToString());
updateAppointment.Show();
MySqlConnection c = new MySqlConnection(SqlUpdater.conString);
MySqlCommand updateCmd = new MySqlCommand();
updateCmd.Connection = c;
c.Open();
updateCmd.CommandText = $"UPDATE customer SET customerName = '{customerNameBox.Text}'";
updateCmd.ExecuteNonQuery();
c.Close();
MessageBox.Show("Appointment Updated");
I figure its the SQL query, but not sure how to limit it to JUST the information on the selected row. Right now, it'll update everyone on the datagridview and database.
Any ideas?
Thanks!
I've tried putting
MainForm.appointmentCalendar.CurrentRow.Cells[1].Value.ToString();
as WHERE in the SQL query, but it returns an "object reference is required" error.
have a column with unique customer ID, then in your query you want
Update customer SET customerName = '{customerNameBox.Text}' where customerID = 'UniqueID'
----- (whatever the ID that you are trying to update is)
probably something like int.Parse(otherDataGrid.selectedRows[0].Cells["ID"].Value.ToString())
#edit
I don't really understand what you're trying to say. You might want to try with parameteres. this would be your query:
Update appointment set type = #type, start = #start, end = #end where customerId = #id
then before you execute the command you say:
updateCmd.Parameters.AddWithValue("#type", typeBox.Text);
and do that for all other parameters too.
Also make sure that your text boxes are not empty, because they most likely are if your query is deleting the data (maybe it's updating it with an empty string)
Related
I have a datagrid in my WPF application. In one column I have an int (column name = Amount).
So for example there will be a number "4" in the cell. I can edit "4" in the DataGrid to "3".
After editing, I will push the button "Update" so my database column Amount will be updated.
It is working, but it update all the cells in the column Amount to the Id number of the chosen row.
This is my code in the xaml.cs file:
private void Update(object sender, RoutedEventArgs e)
{
DataRowView o = (DataRowView)g2.SelectedItem;
int Amount = Convert.ToInt32(o.Row.ItemArray[0]);
try
{
const string query = #"UPDATE [Stock] SET [STOCK].Amount = #Aantal;";
using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"...."))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#Amount", SqlDbType.Int).Value = Amount;
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Update complete");
binddatagrid();
}
catch (Exception ex)
{
MessageBox.Show("Error occurred:\r\n" + ex.Message);
}
}
What am I doing wrong?
Your database query is updating the Amount column in every row in the [Stock] table. You need to add a WHERE clause to your database query so that you only update the [Stock] row in the database that corresponds to the selected row in the DataGrid.
I don't know what your database schema looks like, but I'm assuming that the [Stock] table has an Id column. If so, the query might look something like this:
UPDATE [Stock] SET [Stock].Amount = #Anatal WHERE [Stock].Id = #Id
Notice that the query now has a second parameter, #Id. That means that you'll need to get the Id from the selected row in much the same way that you're currently getting the Amount.
int id = Convert.ToInt32(o.Row.ItemArray[1]);
I used o.Row.ItemArray[1], but I don't know what index the Id will actually be stored at. You'll have to use that index to get the correct Id.
Since your query has a second parameter, you also need to add it to the Parameters collection of the SqlCommand instance. Just like how you're doing with Amount.
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = id;
I am trying to insert new information into my already created table where id = 2019;
I get the error incorrect syntax near WHERE:
private void button6_Click(object sender, EventArgs e)
{
xcon.Open();
SqlDataAdapter xadapter = new SqlDataAdapter();
xadapter.InsertCommand = new SqlCommand("INSERT into dbo.SysX VALUES (#fpp, #sdd, #sff) WHERE id = 2019", xcon);
xadapter.InsertCommand.Parameters.Add("#fpp", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text);
xadapter.InsertCommand.Parameters.Add("#sdd", SqlDbType.Int).Value = Convert.ToInt32(textBox2.Text);
xadapter.InsertCommand.Parameters.Add("#sff", SqlDbType.Int).Value = Convert.ToInt32(textBox3.Text);
xadapter.InsertCommand.ExecuteNonQuery();
xcon.Close();
}
How can I insert new information on click of button where ID = 2019?
You need to change the below line
xadapter.InsertCommand = new SqlCommand("INSERT into dbo.SysX VALUES (#fpp, #sdd, #sff) WHERE id = 2019", xcon);
to the as below line if you want to insert value/row into the table.
xadapter.InsertCommand = new SqlCommand("INSERT into dbo.SysX VALUES (#fpp, #sdd, #sff)", xcon);
If you want to update existing record then you need to replace your SQL Statement as
"Update dbo.SysX Set <Col1> = #fpp, <Col2> = #sdd, ... where id = 2019"
You can check this Answer and this link.
INSERT and UPDATE are two really separate SQL commands. As their name suggests, with INSERT you add new record to a table, with UPDATE you edit existing record, so either you provide a pointer to an existing record to edit it
UPDATE Table SET Column = data WHERE Field = ‘x’
or you just provide a number of values to be inserted
INSERT INTO Table (Columns) VALUES (Data)
On a side note, such insertions or updates are best done with stored procedures, in order to avoid sql injection attacks.
So, I.ve actually googled a lot about that error, but some of the code that had a solution I couldn't understand, mainly because I'm new at c#, so I'll just put the problem as it is.
My professors called it "complex winform". That's basically data from 2 different tables that are linked with an inner join. So far so good.
I work with postgresql btw.
I have 2 main tables. Student (with idstudent, registrationid, yearofstudy) and Persons( with idperson, Name, Telephone, Email, etc). (idstudent = idperson)
There are around 20 PERSONS in my database and 7 STUDENTS. Students are also persons (duuh), ergo idstudent=idperson.
So, I have a combobox where i put a disctinct yearofstudy of all my students and it looks like this.
private void frmComplex1_Load(object sender, EventArgs e)
{
OdbcConnection conexiune;
conexiune = new OdbcConnection();
conexiune.ConnectionString = "Driver={PostgreSQL ANSI};database=postgres;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;fakeoidindex=0;showoidcolumn=0;rowversioning=0;showsystemtables=0;fetch=100;unknownsizes=0;maxvarcharsize=255;maxlongvarcharsize=8190;debug=0;commlog=0;usedeclarefetch=0;textaslongvarchar=1;unknownsaslongvarchar=0;boolsaschar=1;parse=0;extrasystableprefixes=dd_;lfconversion=1;updatablecursors=1;trueisminus1=0;bi=0;byteaaslongvarbinary=0;useserversideprepare=1;lowercaseidentifier=0;gssauthusegss=0;xaopt=1;pwd=irimia96";
conexiune.Open();
OdbcCommand comanda;
comanda = new OdbcCommand();
comanda.CommandText = "SELECT DISTINCT anstudiu from studenti ORDER BY anstudiu asc ";
comanda.Connection = conexiune;
OdbcDataReader cititor;
cititor = comanda.ExecuteReader();
DataSet dsDate;
dsDate = new DataSet();
DataTable tblStudenti;
tblStudenti = new DataTable("studenti");
tblStudenti.Load(cititor);
dsDate.Tables.Add(tblStudenti);
this.cboComplex1.DataSource = dsDate.Tables["studenti"];
this.cboComplex1.DisplayMember = "anstudiu";
this.cboComplex1.ValueMember = "anstudiu";
conexiune.Close();
}
So what im trying to do is, whenever I select a year (1/2/3) from that combobox, to get in return, in my first DataGrindView Information about students that are year 1/2/3 from BOTH STUDENT table and PERSON TABLE. For example: the students from yearofstudy 2 with. IdPerson, Name, Telephone, Email, RegistrationId, Student Id. (I know Student Id and Person Id will get the same value, but I dont care, first let it work)
So i type the script, and get this the datarawview error
private void cboComplex1_SelectedIndexChanged(object sender, EventArgs e)
{
OdbcConnection conexiune;
OdbcCommand comanda;
DataSet dsDate;
OdbcDataReader cititor;
DataTable tblPersoane;
conexiune = new OdbcConnection();
conexiune.ConnectionString = " Driver={PostgreSQL ANSI};database=postgres;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;fakeoidindex=0;showoidcolumn=0;rowversioning=0;showsystemtables=0;fetch=100;unknownsizes=0;maxvarcharsize=255;maxlongvarcharsize=8190;debug=0;commlog=0;usedeclarefetch=0;textaslongvarchar=1;unknownsaslongvarchar=0;boolsaschar=1;parse=0;extrasystableprefixes=dd_;lfconversion=1;updatablecursors=1;trueisminus1=0;bi=0;byteaaslongvarbinary=0;useserversideprepare=1;lowercaseidentifier=0;gssauthusegss=0;xaopt=1;pwd=irimia96";
conexiune.Open();
comanda = new OdbcCommand();
comanda.CommandText = "SELECT * from persoane INNER JOIN studenti on persoane.idpersoana = studenti.idstudent WHERE anstudiu =?";
comanda.Connection = conexiune;
comanda.Parameters.Clear();
comanda.Parameters.AddWithValue("anstudiu", cboComplex1.SelectedValue.ToString());
cititor = comanda.ExecuteReader();
tblPersoane = new DataTable("persoane");
tblPersoane.Load(cititor);
dsDate = new DataSet();
dsDate.Tables.Add(tblPersoane);
dGComplex.DataSource = dsDate;
dGComplex.DataMember = "persoane";
dGComplex.Refresh();
}
Srry for the long post, i'll give you a potato at the end.
Just invert the order of the settings for DisplayMember/ValueMember in relation to the setting of the DataSource property
this.cboComplex1.DisplayMember = "anstudiu";
this.cboComplex1.ValueMember = "anstudiu";
// Move this line after setting the Disply/ValueMember property
this.cboComplex1.DataSource = dsDate.Tables["studenti"];
This should ensure the proper binding of the strings used for Display/ValueMember against the field names of the datatable.
I should add that this mode doesn't catch an error if you mistype one of your field names (for example "anstdiu" will be accepted).
On the contrary, if you set the DataSource before the Display/ValueMember, trying to write an invalid name will get you a runtime exception.
I saw many many articles on this but none helped so far.
My ComboBox name is cbPlan. I want to Retrieve PlanName in it's display but want to actually hold it PlanID.
Following code displays both Names and IDs. I tried ValueMember, DisplayMember, properties but couldn't get it sorted yet.
Finally, even if this works out, how will I get to insert PlanID in another table? Will i use Convert.ToString(cbPlan.Text) - which would bring the PlanName and not the ID.
Please help on this - A big thank you in advance! :)
P.S. PlanID's data type is int.
private void cbPlan_Click(object sender, EventArgs e)
{
cbPlan.Items.Clear();
string pullsub = "select PlanID,PlanName from fbkPlanMaster(nolock)";
string connString = ConfigurationManager.ConnectionStrings["Dbconn"].ToString();
SqlConnection connection = new SqlConnection(connString); // defining sql connection
SqlCommand cmd = new SqlCommand(pullsub, connection);
cmd.CommandText = pullsub;
connection.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
cbPlan.Items.Add(drd["PlanID"]);
cbPlan.Items.Add(drd["PlanName"]);
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
}
}
First of all modifying your approach to add items to your combo-box you should not use Reader. Second, why are you adding PlanID if you don't want to display it?
This code may help you ...
cbPlan.DataSource = dt;
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
You should first get your data from database into some datatable or a dataset as above cbPlan.DataSource = dt;
This will hold your id as ValueMember as an ID and its displayed text will be PlanName. Hope this helps you.
On one form I have a dgv. From another form, I can add an item to the dgv and also place the new item into the SQLite database.
What I'm trying to do is also be able to edit the item from the dgv, and have the edit be saved in the database also.
I have this code for CellEndEdit event:
SetConnection();
sqlconnection.Open();
this.dataGridView1.Rows[e.RowIndex].Selected = true;
this.rowIndex1 = e.RowIndex;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0];
sqlcmd = new SQLiteCommand("UPDATE table1 SET item = #item, quantity = #quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value, sqlconnection);
sqlcmd.Parameters.AddWithValue("#item", this.dataGridView1.Rows[this.rowIndex1].Cells["item1"].Value);
sqlcmd.Parameters.AddWithValue("#quantity", this.dataGridView1.Rows[this.rowIndex1].Cells["quantity1"].Value);
sqlcmd.ExecuteNonQuery();
sqlconnection.Close();
This code works, but only if I load the database to the dgv.
When the program is first opened, the database isn't loaded into the dgv. The problem I run into, is when I add a new item (and its the only item present in the dgv), and I try to edit it (aka. change name.etc.), I get the following error: SQL logic error or missing database
near " ": syntax error
Note: When the dgv is empty and I add a new item, the new item is successfully added to the database table.
Also Note: 'id' is the PRIMARY KEY and AUTOINCREMENTed
The situation you're having here is that when you add a new item to the DGV, you are not providing a value to the ID column. So at the end of the query
"UPDATE table1 SET item = #item, quantity = #quantity WHERE id= " + this.dataGridView1.Rows[this.rowIndex1].Cells["id"].Value
This will become like id = . because the ID column in the DGV is currently empty and is definitely a Syntax Error.
It works when you load data because, you are filling up this column. So the solution is to provide value to the ID column properly when you insert a new item.
After inserting an entry to the db, get the Automatically Incremented ID by using a query
Select last_insert_rowid();
Read the value using reader and apply it to the ID column of the table
This works for me.
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Server=your_server_name;Database=your_db_name;Trusted_Connection=True;"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Courses", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
{
SqlCommandBuilder sqlcmd = new SqlCommandBuilder(da);
DataSet ds = new System.Data.DataSet(); // remove this line
da.Update(this.ds, "Courses");
}
}
}
}
}