I have a database with 8 tables, i fill my datagridview and then save changes using the same block of code for each table, but i can only save 4 of 8 tables, the other 4 tables gives me an error
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records whe i try to save the changes in them
This is how i fill my dataGridView:
{
string script = "SELECT * FROM hatr.rbt;";
mycon = new MySqlConnection(connect);
mycon.Open();
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
SD.DataTable table = new SD.DataTable();
ms_data.Fill(table);
DataSet ds = new DataSet();
dataGridView1.DataSource = table;
mycon.Close();
ds.AcceptChanges();
}
And this is how i save the changes:
{
string script = "SELECT id, name, Model_preparation_R_Hr, Time_for_preparation_hr, Time_for_post_processing_hr, YZV_work FROM rbt;";
mycon = new MySqlConnection(connect);
mycon.Open();
MySqlDataAdapter ms_data = new MySqlDataAdapter(script, connect);
var cb = new MySqlCommandBuilder(ms_data);
cb.GetInsertCommand();
DataSet ds = new DataSet();
ms_data.Update(dataGridView1.DataSource as DataTable);
ms_data.InsertCommand = cb.GetInsertCommand();
ms_data.InsertCommand.CommandText += "; select * from rbt where id = last_insert_id();";
ms_data.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
}
I also know that the error occurs in the line:
ms_data.Update(dataGridView1.DataSource as DataTable);
Both blocks of code are the same for every table, but the second block which is need to save changes in dataGrid for some reason gives me an updateCommand error i mentioned before, i couldn't figure out why i get this error for some tables and why i dont get it for others.
So maybe there is some other way to save changes in dataGridView? Because this is the only one i could come up with for now
I finally have found a reason of the Concurrency violation: the UpdateCommand affected 0 of the expected 1 records error. Considering that i have created my database in MySql Workbench and i was trying to work with it through dataGridView in my App i have found out that there is a conflict between FLOAT fields in MySql Workbench and dataGridView. When you create a float number in MySql Workbench it should be written with a dot like "0.1" and it appears that in dataGridView it should be written with comma like "0,1" so the one float field but in to different situations: in mysql Workbench and dataGridView has two different ways to be written and it occurs an Error, as i see this situation, i can be wrong in some ways of course, but i just recreated all FLOAT fields as DOUBLE and now it works.
Related
I have a table with four text fields but when I execute the following I only get one field in the DataGridview. I am not geting all the records either I dont think. How to fix it so I get all the fields and records? text= table name this is in a function/method. Is it the query thats fouling things up?
string connetionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\Set.mdb;Persist Security Info=False";
string sql = "SELECT Property, PValue, PDefault, PType FROM "+text;
OleDbConnection connection = new OleDbConnection(connetionString);
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, text);
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = text;
There's a myriad of things that could be wrong. But none of them are evidenced in your question.
Your DataGridView might not have the correct columns added, or doesn't have AutoGenerateColumns = true.
You haven't mentioned if the data is actually missing from the dataset, or if it's just your view that's broken. Wouldn't you KNOW you're not getting all the records back? Not just have a hunch? Breakpoint that line, Sir!
Have you tried running that command directly on the database? Are the results good there?
I expect the answer will be that the data is fine, but the view is not showing all the data, Data...
It is working fine if just display the results from a single table.
SqlCeCommand command = new SqlCeCommand("SELECT Student.EnrolNo,Student.St_Name FROM Student", ceConnection);
SqlCeDataAdapter adapter = new SqlCeDataAdapter(command);
DataSet set = new DataSet();
adapter.Fill(set, "Student");
ReportDocument document = new ReportDocument();
document.Load(#"C:\Users\user\documents\visual studio 2012\Projects\Student_Scholarship_management2\Student_Scholarship_management2\MainReport.rpt");
document.SetDataSource(set.Tables[0]);
crystalReportViewer1.ReportSource = document;
Now the above code is working fine as it just references a single table however if i use the query below which accesses record from multiple tables
SqlCeCommand command = new SqlCeCommand("SELECT Student.EnrolNo,Student.St_Name,Campus.C_ID FROM Student INNER JOIN Campus ON Student.Campus_ID=Campus.C_ID", ceConnection);
Only those columns get displayed which are from the Student Table. I have tried importing and linking more tables in through the Database Expert but it is of no use. I have verified the query and the resutls are fine and coming through just not getting displayed in crystal reports.
I have added the table in database expert and have added the relevant column in the report designer. Unfortunately its only displaying the data from one table. What could be causing this?
I would have a look at your set command:
document.SetDataSource(set.Tables[0]);
To me that seems to be setting only the first table in your DataSet.
I have a similar situation in the app I'm working on and this is my code (which is passing in about 10 tables):
var data = new DataSet();
//Do stuff to populate the dataset
report.SetDataSource(data);
The final line sets the datasource of your report to be all the tables in the DataSet.
When you call:
adapter.Fill(set, "Student");
In that moment, the table schema in dataset is built. So, if you fill below with other columns, only the columns from the first fill will be considered. A solution for you would be to replace:
SqlCeCommand command = new SqlCeCommand("SELECT Student.EnrolNo,Student.St_Name FROM Student", ceConnection);
with
SqlCeCommand command = new SqlCeCommand("SELECT Student.EnrolNo,Student.St_Name, null as C_ID FROM Student", ceConnection);
I got two datatables from a mdb file using oledb and modified it.
accessConnection.Open();
string selectQuery = "SELECT * FROM Students";
DataAdapter = new OleDbDataAdapter(selectQuery, accessConnection);
DataAdapter.Fill(StudentsDataTable);
DataAdapter.SelectCommand.CommandText = "SELECT * FROM Teachers";
DataAdapter.Fill(TeachersDataTable);
// modified the two datatables
// ...
However, I have a problem in updating the two tables back into the mdb file. I can't update StudentsDataTable because the DataAdapter select command was already changed to select TeachersDataTable. When I handle only one DataTable, I don't have this kind of problem.
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(StudentsDataTable); <-- exception error occur that columns don't match.
DataAdapter.Update(TeachersDataTable);
Do you have any ideas for updating two datatables using one DataAdapter? or Should I have separate DataAdapters for the two tables?
Essentially you have to create two instances.
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(TeachersDataTable);
DataAdapter.SelectCommand.CommandText = "SELECT * FROM Students";
DataAdapter.UpdateCommand = new OleDbCommandBuilder(DataAdapter).GetUpdateCommand();
DataAdapter.Update(StudentsDataTable);
The main issue is your DataAdapter is set to Teachers table as it was the last command set on it.
I am trying to use MySqlDatAdapter to update a MySql table. But, the table never updates!!! I did this before but with SQL server. Is there anything else that is specific to MySql that I am missing in my code?
DataTable myTable = new DataTable("testtable");
MySqlConnection mySqlCon = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBConStr"].ConnectionString);
MySqlCommand mySqlCmd = new MySqlCommand("SELECT * FROM testtable WHERE Name = 'Tom'");
mySqlCmd.Connection = mySqlCon;
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
mySqlCon.Open();
adapter.Fill(myTable);
myTable.Rows[0]["Name"] = "Was Tom";
myTable.AcceptChanges();
adapter.Update(myTable);
mySqlCon.Close();
Thanks
Remove myTable.AcceptChanges() before the update. Othwerwise that will set all rows RowState to Unchanged, hence the DataAdapter will not know that something was changed.
adapter.Update(myTable) will call AcceptChanges itself after the update is finished.
So...
myTable.Rows[0]["Name"] = "Was Tom";
//myTable.AcceptChanges();
adapter.Update(myTable);
My some one need to look into the following solution; In other scenario people may need different solution. Even Don't do any manipulation with Datatable when you Debug at Run-time like this,
myTable.GetChanges(); // Return Any of Chnages Made without applying myTable.Accepchanges()
myTable.GetChanges(DataRowState.Added); // Return added rows without applying myTable.Accepchanges()
myTable.GetChanges(DataRowState.Deleted);
myTable.GetChanges(DataRowState.Detached);
myTable.GetChanges(DataRowState.Modified);
myTable.GetChanges(DataRowState.Unchanged);
You may get Data According to the above commands. So better try to debug before you pass the datatable to update or insert or delete command.
If myTable.GetChanges() return null then you can SetAdded() or SetModified() back to your DataTable;
foreach(DataRow row in myTable.Rows)
{
row.SetAdded(); // For Insert Command
row.SetModified(); // For Update Command
}
I've written a small form that reads the data from a database table (SQL CE 3.5) and displays it in a DataGridView control. This works fine. I then modified it to make a change to the data before displaying it, which also seems to work fine with the exception that it doesn't seem to actually commit the changes to the database. The code is as follows:
using (SqlCeConnection conn = new SqlCeConnection(
Properties.Settings.Default.Form1ConnectionString
)) {
conn.Open();
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter(
"SELECT * FROM People", conn
)) {
//Database update command
adapter.UpdateCommand = new SqlCeCommand(
"UPDATE People SET name = #name " +
"WHERE id = #id", conn);
adapter.UpdateCommand.Parameters.Add(
"#name", SqlDbType.NVarChar, 100, "name");
SqlCeParameter idParameter = adapter.UpdateCommand.Parameters.Add(
"#id", SqlDbType.Int);
idParameter.SourceColumn = "id";
idParameter.SourceVersion = DataRowVersion.Original;
//Create dataset
DataSet myDataSet = new DataSet("myDataSet");
DataTable people = myDataSet.Tables.Add("People");
//Edit dataset
adapter.Fill(myDataSet, "People");
people.Rows[0].SetField("name", "New Name!");
adapter.Update(people);
//Display the table contents in the form datagridview
this.dataGridView1.DataSource=people;
}
}
The form displays like so:
Looking at the table via Visual Studio's Server Explorer however, doesn't show any change to the table.
What am I doing wrong?
I found it. It took days but I found it.
Properties.Settings.Default.Form1ConnectionString is "Data Source=|DataDirectory|\Form1.sdf". The update works if I replace the automatically generated "|DataDirectory|" with the actual path. Oddly enough reading from the database works either way.
Shouldn't the update line be
adapter.Update(myDataSet, "People")
I would make sure the DataSet believes it's been changed. Invoke DataSet.HasChanges (returns bool) and DataSet.GetChanges, which returns a delta of the DataSet from the original.
Have you also tried this against Sql Server Express just to eliminate any issues with the CE data adapter?