Link to home
Start Free TrialLog in
Avatar of PoeticAudio
PoeticAudio

asked on

Writing data to a database from a datagrid

How would I write data back into a database using a DataGrid on a non-web project?

Thanks,
Avatar of stone123
stone123

Two solutions are provided here. For simplification, I only give examples of using OleDb type of objects. You can replace all OleDb* objects to Sql* objects if necessary.

Solution #1:

I presume that you are using an OleDbDataApapter and a DataSet object between your database and datagird.
Then use Update method to save your datagrid data back to database:

oleDbDataAdapter1.Update(myDataSet, "myTableName");


Solution #2: use embedded SQL statement.

Create an OleDbConnection to open a connection to your database, and an OleDbCommand object to execute SQL statement.

OleDbConnection myConn;
OleDbCommand cmd;

myConn.Open();
cmd.CommandText = "UPDATE myTableName SET theColumnName= @myValue WHERE nID = @myID";
cmd.Parameters.Add("@myValue", myValue);
cmd.Parameters.Add("@myID", theID);
cmd.ExecuteNonQuery();
myConn.Close();
In my second approach,

To initiate your objects, use:

myConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myFolder\\myDataBase.mdb");
cmd = new OleDbCommand("", myConn);

This example uses Microsoft Acess database.

If you have difficulty of making it work with other type of database, let me know.

stone.
Avatar of PoeticAudio

ASKER

I'm getting an exception:

I'm trying to use
dataAdapter1.Update(dataSet1, "tblClient");

but i'm getting this

"Update requires a valid UpdateCommand when passed DataRow collection with modified rows."


Sorry, i'm totally new to this
ASKER CERTIFIED SOLUTION
Avatar of stone123
stone123

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial