Updating a table on DB considering changes on a grid in C# - c#

I'm filling a Data Grid in C# (WinForms) via a System.Data.DataTable. DataTable is filled from a DB table via ODP.
I have a data navigator in Data Grid for updating, deleting and inserting rows.
I want to use DataTable to commit all changes made in Data Grid to the database.
I have to use OracleDataAdapter but I couldn't figure out how to achieve this.
What kind of a CommandText should I use to achieve all three commands (update, delete, insert)?
The code below didn't work (maybe because CommandText I inserted is not appropriate)
public void ExecuteNonQuery(string commandText, OracleCommand oracleCommand, CommandType commandType, DataTable dataTable)
{
oracleCommand.CommandText = commandText;
oracleCommand.CommandType = commandType;
try
{
oracleCommand.Connection = m_Connection;
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(oracleCommand);
oracleDataAdapter.Update(dataTable);
}
catch (Exception)
{
LoggerTrace.Instance.Write(TraceEventType.Error, LoggerTrace.LoggerTraceSource.DatabaseManagerError, "Query could not be executed!");
throw;
}
}

for insert create a new row in data table and insert into data table ,for update update the value and finally make save change of data set or data table

OracleCommandBuilder producess the appropriate insert, update and delete queries after the select query is inserted.
string selectCommand = "select * from Table";
oracleDataAdapter.SelectCommand = new OracleCommand(selectCommand, m_Connection);
OracleCommandBuilder cmdBuilder = new OracleCommandBuilder(oracleDataAdapter);
DataTable dataTable = new DataTable();
oracleDataAdapter.Fill(dataTable);
After OracleCommandBuilder build the command this way you can execute any updates in the DataTable like this:
oracleDataAdapter.Update(dataTable);
Sequences, virtual columns etc. are not allowed.

Related

My gridcontrol doesn't show datatable connected SQL Server

In this form, I have just one gridcontrol and this datasource is datatable connected to SQL Server.
Bottom of the gridcontrol there are four buttons named select, insert, delete, modify gridcontrol.
This is my code, and it has click event when insert button is clicked.
private void InputButton_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(mssql))
{
conn.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("Insert into [Department] (부서코드, 부서명) values (#부서코드, #부서명)", conn);
cmd.Parameters.AddWithValue("#부서코드", "2101");
cmd.Parameters.AddWithValue("#부서명", "영업부");
sqlDataAdapter.InsertCommand = cmd;
int result = cmd.ExecuteNonQuery();
if (result < 0)
{
MessageBox.Show("There are errors when inserting data");
}
else
{
sqlDataAdapter.Update(dataTable);
gridControl1.RefreshDataSource();
conn.Close();
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When I click insert button, there are not any event in gridcontrol so I don't see any change of insert query. However, close form and reopen form, then I can see my insert query in gridcontrol.
Even I use gridcontrol.refreshdatasource but I don't know what I can't see any changes soon after I click
insert button. Is there any answers?
Even I tried use try catch, but I don't know my issue. I want to show gridcontrol.refreshdatasource when I click insert query.
To insert SQL Server data using a GridControl and DataTable in C# Winform, you can follow these steps:
Create a connection string to connect to the SQL Server database. You can use the SqlConnection class to create the connection string.
string connectionString ="Server<server_name>;Database<database_name>;User Id=<username>;Password=<password>;";
Create a DataTable object to store the data that will be displayed in the GridControl. You can add columns to the DataTable object to match the columns in the SQL Server table.
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
Create a SqlDataAdapter object and use it to fill the DataTable object with data from the SQL Server table. You can use the SELECT statement to retrieve the data.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM <table_name>", connectionString);
adapter.Fill(dt);
Set the DataSource property of the GridControl to the DataTable object to display the data in the GridControl.
gridControl1.DataSource = dt;
Add a new row to the DataTable object using the NewRow method, and set the values of the columns.
DataRow row = dt.NewRow();
row["ID"] = 1;
row["Name"] = "Bob Ross";
row["Age"] = 52;
dt.Rows.Add(row);
Create a SqlCommand object to insert the data into the SQL Server table. You can use the INSERT INTO statement to insert the data.
SqlCommand cmd = new SqlCommand("INSERT INTO <table_name> (ID, Name, Age) VALUES (#ID, #Name, #Age)", connection);
cmd.Parameters.AddWithValue("#ID", row["ID"]);
cmd.Parameters.AddWithValue("#Name", row["Name"]);
cmd.Parameters.AddWithValue("#Age", row["Age"]);
cmd.ExecuteNonQuery();
Refresh the DataTable object and the GridControl to reflect the changes.
dt.Clear();
adapter.Fill(dt);
gridControl1.RefreshDataSource();
Note that you should handle any exceptions that may occur while inserting data into the SQL Server table, and also make sure to dispose of any database connections, commands, and adapters after use.
Hope this helps.

How to save a DataTable to SQLite DB?

I'm trying to perform a simple task, however, all the examples I'm finding do not work.
I have a very simple case:
I have a dataTable that belongs to a dataSet. It is populated from some text file that I parsed (not CSV).
I just want to save that dataTable into SQLite DB, where I have an empty table with the same schema (same number of columns and format of columns).
I have this method:
public static void UpdateTable(string dbpath, DataSet dataSet, string tableName)
{
using (SQLiteConnection db = new SQLiteConnection($"URI=file:{dbpath}"))
{
db.Open();
dataSet.AcceptChanges();
SQLiteDataAdapter DataAdapter = new SQLiteDataAdapter("select * from " + tableName, db);
DataAdapter.AcceptChangesDuringUpdate = true;
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(DataAdapter);
DataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand();
DataAdapter.Update(dataSet, tableName);
}
}
This is the last way I tried. All I'm getting is the same empty table in SQLite DB.
All I want to do is just save a table into a DB. I guess I can do that row by row, but I know there is a way to do that in one command.
Could you please help me write a functioning method?

Delete all access database table data

I have an access database that I am manipulating with C#.
I have connected to it, retrieved a data-set from it and can add rows to a table. Now I am trying to clear a table and I am unable to get it to work.
I have tried TRUNCATE TABLE table_name but that throws an exception saying that I must use either DELETE, INSERT, PROCEDURE, SELECT or UPDATE and I have tried Delete FROM table_name However that throws an DBConcurrenceyException.
Here is what I have to tried to clear the table:
private void ClearBut_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableClear = new OleDbDataAdapter();
OleDbCommand command;
command = new OleDbCommand("DELETE FROM TestTable", con);
dtaAdpTestTableClear.DeleteCommand = command;
foreach (DataRow row in dsWCSDHDB.Tables["TestTable"].Rows)
{
row.Delete();
}
dtaAdpTestTableClear.Update(dsWCSDHDB.Tables["TestTable"]);
}
My other add method
private void Add_Click(object sender, EventArgs e)
{
OleDbDataAdapter dtaAdpTestTableInsertNewRow = new OleDbDataAdapter();
OleDbCommand command;
// Create the InsertCommand.
// This is needed as DataAdaptor.InsertCommand() is called during the update to insert the row into the database. It requires an insert query
command = new OleDbCommand("INSERT INTO TestTable (id, someData) " +"VALUES (?, ?)", con); //We create a dbcommand the command is, Querytype, what we are doing with it, what table, (columns we are using), concat, Values we will be adding(as ? for now as we will pass this data in latter), connection to the database
command.Parameters.Add("id", OleDbType.Char, 5, "id"); //this is where we add a parameter to the command function. we add one per column in the row (columns we are using name, value type, column length, source column, these parameters will replace the ? in the query above
command.Parameters.Add("someData", OleDbType.VarChar, 40, "someData");
dtaAdpTestTableInsertNewRow.InsertCommand = command;// we attach this command to the Insert command function of the adapter that we are using
//Create the new row
DataRow row = dsWCSDHDB.Tables["TestTable"].NewRow(); //Create a new empty row that is formated for the TestTable table
row["someData"] = AddValueTextBox.Text.ToString();// add in the values
//Add the new row to the dataset table
dsWCSDHDB.Tables["TestTable"].Rows.Add(row); //adds this new row to the clients dataset
//Updates the database table with the values of the clients dataset Table
//For this to work you need to build a proper data adapter that is using a query taylered for the table you are using.
//Unfortunately although it would be nice to be able to add and use tables to the database with out changing the code you cant build a generic one that works for all tables in the database.
//this is because different tables can have different fields and column lengths .
//there is a example of how to build one below
//Update the database table with the values of the clients dataset Table
dtaAdpTestTableInsertNewRow.Update(dsWCSDHDB.Tables["TestTable"]); // using the adapter that we created above we update the database with the clients dataset.
}
You will just need to call ExecuteNonQuery
private void ClearBut_Click(object sender, EventArgs e)
{
string comand = "DELETE FROM TestTable";
OleDbCommand cmd = new OleDbCommand(comand, con);
cmd.ExecuteNonQuery();
}

Visual Studio 2013 fill DataGrid

I'm trying to read data from a SQLite database. Then I'd like to fill it into my DataGrid, but the following code doesn't work (dataUrl is the DataGrid-Object):
string sql = "SELECT rowid, url FROM urls WHERE url LIKE '%#search%'";
SQLiteConnection myConnection = new SQLiteConnection(#"Data Source=C:\URL Store\URL Store\bin\Release\urlStore.sqlite;Version=3;Password=*censored*;");
SQLiteCommand command = new SQLiteCommand(sql, myConnection);
command.Parameters.AddWithValue("#search", txtSearch.Text);
myConnection.Open();
command.ExecuteNonQuery();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataSet set = new DataSet();
try
{
//
//ESPECIALLY THIS PART IS IMPORTANT TO ME
//
adapter.Fill(set);
DataTable table = set.Tables[0];
dataUrl.DataContext = table;
}
catch (Exception ex)
{
MessageBox.Show("Error loading data!");
}
It does't even throw an exception.
You should set ItemsSource instead of DataContext and for that you need to get DataView as it only accepts IEnumerable:
dataUrl.ItemsSource = table.DefaultView;
or
dataUrl.ItemsSource = new DataView(table);
also remove command.ExecuteNonQuery();
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
also, because you use parameters and AddWithValue(..), your query should look like this:
string sql = "SELECT rowid, url FROM urls WHERE url LIKE #search";
and you add parameter like this instead:
command.Parameters.AddWithValue("#search", "%" + txtSearch.Text + "%");
which is the whole point of using parameters

C# write datagridview data into a SQL Server table

I have a four column table in a SQL Server database. The info for the first three columns is supplied by another source. Column 4 is set to null by default.
I then have a win form with a datatable that populates with the information from the SQL Server database using the following code:
public DataTable populateFormList()
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.sqlConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM of_formlist_raw", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
datagridview2.DataSource = populateFormList();
datagridview2.Refresh();
Now that works fine in obtaining my data.
The user can then make changes to the null values in column 4.
How can I easily write these changes from the datatable back into the SQL Server table?
In other words, once the on screen datatable has additional values, how can I then store the updated information back in the SQL Server database from which it was originally obtained from?
Thanks.
Try something like this and just pass (DataTable)datagridview2.DataSource as the data table:
private static void BulkInsertToSQL(DataTable dt, string tableName)
{
using (SqlConnection con = new SqlConnection(_DB))
{
SqlBulkCopy sbc = new SqlBulkCopy(con);
sbc.DestinationTableName = tableName;
//if your DB col names don’t match your data table column names 100%
//then relate the source data table column names with the destination DB cols
sbc.ColumnMappings.Add("DBAttributeName1", "DTColumnName1");
sbc.ColumnMappings.Add("DBAttributeName2", "DTColumnName2");
sbc.ColumnMappings.Add("DBAttributeName3", "DTColumnName3");
sbc.ColumnMappings.Add("DBAttributeName4", "DTColumnName4");
con.Open();
sbc.WriteToServer(dt);
con.Close();
}
}
2 options, with or without TableAdapter.
I would recommend to read this in MSDN for TableAdapter
They're using BindingSources too, which are excellent components, easy-to-use.
Without TableAdapter, read this, the "Update Records Using Command Objects" part.

Categories