I'm attempting to update a SQL table from C# project datagridview "Work_Table". However when I attempt to make the update I get this error
"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'"
Any ideas?
Here is my code below:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"Select * from person.addresstype";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Update(ds, "Work_Table");
MessageBox.Show("Saved");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.
You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.
Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.
private string connString = "Your connection string";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
try
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
{
dAdapter.Update(dt);
}
MessageBox.Show("Saved");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
Related
this same code has worked for several other programs, however i can not get it to function with this program for some reason. what is happening is i select a file location on my desktop to read from, but the program keeps trying to open the file from inside the program files of where i have this program saved.
MessageBox.Show(PATHTEXTBOX.Text);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath;
string query = "select * from Vendors";
OleDbConnection connect = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand(query, connect);
connect.Open();
OleDbDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable.DefaultView;
connect.Close();
Querying the database using the "SqlDataAdapter" object was successful. I made a case to reproduce your problem and realized the query to the database.
UI page:
Vendors table data:
Test Results:
Code logic:
Query the database by clicking the test button.
Bind the DataGridView control by using code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connStr = #"Data Source=(localdb)\ProjectModels;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//Create an instance of SqlConnection
SqlConnection conn = null;
try
{
conn = new SqlConnection(connStr);
//open database
conn.Open();
string sql = "select * from Vendors";
//Create an object of the SqlDataAdapter class
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
//Create an object of the DataSet class
DataSet ds = new DataSet();
//Use the SqlDataAdapter object sda to fill the new lookup results into the DataSet object ds
sda.Fill(ds);
//Set the DataSource property of the table control
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("An error occurred!" + ex.Message);
}
finally
{
if (conn != null)
{
//Close the database connection
conn.Close();
}
}
}
}
It may be helpful to check your database connection string. Hope that helps you.
I need to transfer the table's content to the same table located in another database, and I write this simple code using the C# dataAdapter.Fill() and dataAdapter.Update(), but it's seems not working like I supposed.
SqlConnection sqlConnection = new SqlConnection(strSqlConnectionString);
SqlConnection sqlConnection2 = new SqlConnection(strSqlConnectionString2);
sqlConnection.Open();
sqlConnection2.Open();
DataSet CustomerDataSet = new DataSet();
SqlDataAdapter sqlDA;
SqlDataAdapter sql2DA;
SqlCommandBuilder sqlCmdBuilder;
SqlCommandBuilder sqlCmdBuilder2;
sqlDA = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection);
sqlDA2 = new SqlDataAdapter("SELECT * FROM Articolo;", sqlConnection2);
sqlCmdBuilder = new SqlCommandBuilder(sqlDA);
sqlCmdBuilder2 = new SqlCommandBuilder(sqlDA2);
sqlDA.Fill(CustomerDataSet, "Articolo");
sqlDA2.Fill(CustomerDataSet, "Articolo");
sqlDA2.Update(CustomerDataSet, "Articolo");`
What I want to do is to have the second db(string connection: strSqlConnectionString2) with updated data, taken from the first db, exploiting the functionality of dataAdapter.Fill() + dataAdapter.Update().
Is this possible? And can I do the same things but with Access db as a second db?
Can you try it this way?
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)
You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}
I have a desktop application project. In entry page a datagridview shows the existing items in database. Now when I entry new Item I want to insert it directly in datagridview. That mean I want to reload/refresh datagridview. My database is in MS Access.
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(#ID,#Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#ID",txtID.Text);
cmd.Parameters.AddWithValue("#Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[Note: When I use sql database then it works fine.]
The dbDataAdapterClass (the one that OleDbDataAdapter inherits from) has a SelectCommand, UpdateCommand and InsertCommand. These are responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.
so fulfill the requirements, adding an update command to the adapter.
dataadapter = new OleDbDataAdapter(sql, connection);
Add below code after above line, OleDbCommandBuilder will generate commands for you.
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
This tutorial should help you out.
I am trying to save a dataset to a database. I got a dataset from another class, Now changes will be made on the form by a user on a datagridview, then the changed Dataset needs to be saved in the database.
I am using the below code; Its not generating any errors, but the data is not being saved in the database.
public class myForm
{
DataSet myDataSet = new DataSet();
public void PouplateGridView()
{
try
{
SqlService sql = new SqlService(connectionString); // Valid Connection String, No Errors
myDataSet = sql.ExecuteSqlDataSet("SELECT * FROM Qualification"); // Returns a DataSet
myDataGridView.DataSource = myDataSet.Tables[0];
myDataGridView.AutoGenerateColumns = true;
myDataGridView.AutoResizeColumns();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException + Environment.NewLine + ex.Message, "Error");
this.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//myDataSet.AcceptChanges();EDIT:Don't know why, but this line wasn't letting the chane in db happen.
SqlCommand sc = new SqlCommand("SELECT * FROM Qualification", sql.Connection); //ADDED after Replies
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(da); //ADDED after replies
da.Update(myDataSet.Tables[0]);
}
}
public class mySqlService
{
public DataSet ExecuteSqlDataSet(string sql)
{
SqlCommand cmd = new SqlCommand();
this.Connect();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandTimeout = this.CommandTimeout;
cmd.Connection = _connection;
if (_transaction != null) cmd.Transaction = _transaction;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds);
da.Dispose();
cmd.Dispose();
if (this.AutoCloseConnection) this.Disconnect();
return ds;
}
}
What am I doing wrong here? There are ways on the web to save the dataset, if the datset is created, edited and saved in the same class etc., BUT I would like to have the select dataset method in the mySqlService class. How should I, now can save the dataset to the database?
EDIT:
I have commented the three lines that were required to make the code work. The code works now.
In order to run Update method of SqlDataAdapter you must have to configure InsertCommand, DeleteCommand and UpdateCommand properties along with SelectCommand of SqlDataAdapter or construct the SqlCommandBuilder object which configure these commands implicitly.
Hey try following this tutorial here http://support.microsoft.com/kb/308507 first and then adapt it to your needs.