Unable to add new entry in datatable c# - c#

i'm trying to add a new row to my datatable.
I've no error while running this code but nothing happened in my table.
Here's my code :
string table = "`DONNEE ENTRANT`";
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * From " + table, _conn);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapter);
DataTable dataTable = new DataTable(table);
adapter.Fill(dataTable);
DataRow row = dataTable.NewRow();
row["CODE LIAISON"] = "TEST";
dataTable.Rows.Add(row);
dataTable.AcceptChanges();
adapter.Update(dataTable);
Any idea what i'm doing wrong (in this way, I know that we can run command with oleDb but really don't like this way ...).
Thanks

Based on what you're doing it appears you want that new row to end up in the database. So remove this line:
dataTable.AcceptChanges();
because that's changing the RowState to Unchanged and you need it left at Added. Further, you need to make sure that your adapter has an InsertStatement defined so it can use it.

I would use [] instead of `` but I believe the answer to correct your problem was already given by #Michael Perrenoud

Related

Adding Row to datatable in dataset

I am trying to copy a row from one table to another in same dataset.
code I am using
dsFrom.Tables["asd2"].Rows.Add(dsFrom.Tables["asd"].Rows[0].ItemArray);
I am getting an NullRefferenceException. I've determined that Rows are null, even though there is data in both tables. Can anyone explain why is this happening? Or maybe there is another solution for my problem.
Thanks
EDIT
This is how I am loading data in them
string query = #"select * from table1;
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet dsFrom = new DataSet();
da.Fill(dsFrom, "asd");
da.Fill(dsFrom, "asd2");
May be you should try to copy rows by this way:
foreach (var row in dsFrom.Tables["asd"].Rows)
{
dsFrom.Tables["asd2"].ImportRow(row);
}

How to create columns with the names from a sqlite table in a dataGridView

I'm trying to search for a code entered by the user in a sqlite table if it's found add the row to a dataGridView. the problem is that the code I'm using clears the datagrid every time I add a new row.
Here is the code I'm using
DataTable dt = new DataTable();
String insSQL = "select * from Produtos where codigo =" + txtCodigo.Text;
String strConn = #"Data Source=C:\caixa.sqlite";
SQLiteConnection conn = new SQLiteConnection(strConn);
SQLiteDataAdapter da = new SQLiteDataAdapter(insSQL, strConn);
da.Fill(dt);
dataGridViewProdutos.DataSource = dt.DefaultView;
I tried to change the dataGridViewProdutos.datasource to dataGridViewProdutos.Rows.add(dt); them it adds a row but always empty.
I fixed it removing the DataTable dt = new DataTable(); from the loop. I also changed the dt.DefeulView to only dt as sugested by N4TKD and Im seeing no diference so Im using it.
Also thanks for the links it was very helpfull since I was struggling to make my colums fill the dataGridView space.

Updating using DataTable in database table?

I have a table which has some 100-200 records.
I have fetch those records into a dataset.
Now i am looping through all the records using foreach
dataset.Tables[0].AsEnumerable()
I want to update a column for each record in the loop. How can i do this. Using the same dataset.
I'm Assumng your using a Data Adapter to Fill the Data Set, with a Select Command?
To edit the data in your Data Table and save changes back to your database you will require an Update Command for you Data Adapter. Something like this :-
SQLConnection connector = new SQLConnection(#"Your connection string");
SQLAdaptor Adaptor = new SQLAdaptor();
Updatecmd = new sqlDbCommand("UPDATE YOURTABLE SET FIELD1= #FIELD1, FIELD2= #FIELD2 WHERE ID = #ID", connector);
You will also need to Add Parameters for the fields :-
Updatecmd.Parameters.Add("#FIELD1", SQLDbType.VarCHar, 8, "FIELD1");
Updatecmd.Parameters.Add("#FIELD2", SQLDbType.VarCHar, 8, "FIELD2");
var param = Updatecmd.Parameters.Add("#ID", SqlDbType.Interger, 6, "ID");
param.SourceVersion = DataRowVersion.Original;
Once you have created an Update Command with the correct SQL statement, and added the parameters, you need to assign this as the Insert Command for you Data Adapter :-
Adaptor.UpdateCommand = Updatecmd;
You will need to read up on doing this yourself, go through some examples, this is a rough guide.
The next step is to Enumerate through your data table, you dont need LINQ, you can do this :-
foreach(DataRow row in Dataset.Tables[0].Rows)
{
row["YourColumn"] = YOURVALUE;
}
One this is finished, you need to call the Update() method of yout Data Adapter like so :-
DataAdapter.Update(dataset.Tables[0]);
What happens here, is the Data Adapter calls the Update command and saves the changes back to the database.
Please Note, If wish to ADD new rows to the Database, you will require am INSERT Command for the Data Adapter.
This is very roughly coded out, from the top of my head, so the syntax may be slightly out. But will hopefully help.
You should use original DataAdapter (adapter in code below) that was used to fill DataSet and call Update method, you will need CommandBuilder also, it depends what DB you are using, here is the example for SQL server :
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(dataset);
dataset.AcceptChanges();
Here is the good example :
http://support.microsoft.com/kb/307587
The steps would be something like:
- create a new DataColumn[^]
- add it to the data table's Columns[^] collection
- Create a DataRow [^] for example using NewRow[^]
- Modify the values of the row as per needed using Item[^] indexer
- add the row to Rows[^] collection
- after succesful modifications AcceptChanges[^]
Like this:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("ProductName");
table.Rows.Add(1, "Chai");
table.Rows.Add(2, "Queso Cabrales");
table.Rows.Add(3, "Tofu");
EnumerableRowCollection<DataRow> Rows = table.AsEnumerable();
foreach (DataRow Row in Rows)
Row["ID"] = (int)Row["ID"] * 2;
Add the column like below.
dataset.Tables[0].Columns.Add(new DataColumn ("columnname"));
Update the columns values like below.
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
dataset.Tables[0].Rows[i]["columnname"] = "new value here";
}
Update Database
dataset.AcceptChanges();

DataAdapter.Update() does not update data in DB

I've got an assignment which requires me to update the northwind database,
I've done everything like the tutorials say as follows
I fill The DataTable Using The DataAdapter.Fill(table).
I build the Delete,Insert,Update Commands using CommangBuilder
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.DeleteCommand = builder.GetDeleteCommand(true);
adapter.UpdateCommand = builder.GetUpdateCommand(true);
adapter.InsertCommand = builder.GetInsertCommand(true);
adapter.Fill(employees_table);
I also set a primary key for the table:
DataColumn[] employees_keys = new DataColumn[2];
employees_keys[0] = employees.Columns["EmployeeID"];
employees_table.PrimaryKey = employees_keys;
Now I've attempted to delete and add a row:
// accepts an employee object and creates a new new row with the appropriate values for
// an employee table row
DataRow row = ConvertEmployeeToRow(employeeToAdd);
employee_table.Rows.Add(row);`
and deleting a row:
DataRow row = employees.Rows.Find(employeeToDismiss.ID);
employees.Rows.Remove(row);
I should also point out that I've attempted to use row.SetAdded() and row.Delete()
Anyway, at the end when I try to update the database
int k = employees_adapter.Update(employees_table);
on added rows sometimes k get valued, on remove never, and in either case nothing really gets updated at all in the database itself.
Any insight of what I'm doing wrong?
Make sure you're calling employee_table.AcceptChanges() after the call to Update() to save the changes to the database.
Check if the CommandBuilder really makes an Update command for you, like this:
MessageBox.Show(adapter.UpdateCommand.CommandText);
If the primary key info is missing it won't build the update command at all!
I am little confuse here your SqlDataAdapter name is adapter and you are doing updation in employees_adapter.The steps are so simple to work with SqlDataAdapter just follow theses
Step No 1:
SqlDataAdapter adapter = new SqlDataAdapter(selectStr, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable employees_table= new DataTable ();
adapter.Fill(employees_table);
Step No 2:
After you got the data in dataset start manipulation on it..
To insert :
DataRow MyRow = employees_table.NewRow();
//Now Fill data in MyRow
employees_table.Tables[0].Rows.Add(MyRow);
employees_table.AcceptChanges();
adapter.Update(employees_table);
To Delete :
/get only the rows you want
DataRow[] result = employees_table.Select("ID ="+id); //id will be provided by you
//Now do here data updation
employees_table.AcceptChanges()
adapter.Update(employees_table);
Like wise you can apply updation..But after doing any changes must call
table.AcceptChanges() and then'adapter.Update(employees_table)'

bind more than one dataGridView to MySQL database

I have MySQL database with four tables, and I've written form an example binding method. But this solution works well only with one table. If I bind more than one, dataGridViews will be filled with info, but Update and Delete commands work badly.
public void Bind(DataGridView dataGridView, string tableName)
{
string query = "SELECT * FROM " + tableName;
mySqlDataAdapter = new MySqlDataAdapter(query, conn);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataTable = new DataTable();
mySqlDataAdapter.Fill(dataTable);
bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
dataGridView.DataSource = bindingSource;
}
Should I use different mySqlDataAdapter or mySqlCommandBuilder for each new table? I've used different DataTable and BindingSource objects, but when I inserted new row in one table, I had an exception that I left empty field in other table. Any solutions or tips for this problem?
Thanks in advance!
Better late than never I guess...
I have an application that loads different tables into the same DataGridView using Visual Studio 2013. So far it is working!
1. DataTable
You certainly need to create a new one for each different table you want to load, otherwise you can not clear out the old data. You might think that
dataTable.Clear()
would do the trick but no, it leaves the old column headers behind so your new table is loaded to the right of all the old columns :-(. Although interestingly if your new table has a column with the same name as the old it merges them!
2. MySqlAdapter
I currently create a new one for each table, but at the very least your sql query is changing so you need to create a new SelectCommand:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `" + tableName + "`", conn);
sqlAdapter.SelectCommand = cmd;
I've tried this and it seems to work, but actually it is simpler to just create a new MySqlAdapter and performance really isn't an issue at this point!
3. SqlCommandBuilder
Yes you should create a new one because the update and delete commands will be different. I don't use a class variable but create one dynamically (i.e. as a local variable) when I need it.
4. BindingSource
I don't believe you need a new BindingSource, but I haven't used them very much so can't be certain.

Categories

Resources