[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 185
  • Last Modified:

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,
0
PoeticAudio
Asked:
PoeticAudio
  • 3
1 Solution
 
stone123Commented:
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();
0
 
stone123Commented:
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.
0
 
PoeticAudioAuthor Commented:
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
0
 
stone123Commented:
You can write code to define the OleDbUpdateCommand.CommandText, which is basically a SQL statement, for your OleDbDataAdapter object.

Alternatively, if you create the OleDbDataAdapter object by Data Adapter Configuration Wizard, you should be able to set it there.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now