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.
Related
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);
}
}
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.
For some reasons, i need to write my own sqlquery tool. it generally works.
But when i select a table which contains a binary type, it gives me the error i've shown it below.
I used a DatagridView. My code is below.
private void button1_Click(object sender, EventArgs e)
{
string SQL = txtSQL.Text.Trim().ToString();
try
{
gridResult.DataSource = getDataset(SQL).Tables[0];
}
catch (SqlException err)
{
MessageBox.Show("Error : " + err.Message + "-" + err.Number);
}
}
public DataSet getDataset(string SQL)
{
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}
I wonder, Is there any way to prevent showing binary area or prevent giving error? What should do now? Or do you have any idea how can i detect the type of binary field when loading into the gridview programatically?
I want to select all customer information where customerid = the selected customerid stored in the combo box and show the result in datagridview I tried this code but the gridview doesnot show result.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
int id = Convert.ToInt32(comboBox1.SelectedValue);
string cmdstring=string.Format("select *from customers where customer_id={0}",id);
SqlCommand cmd = new SqlCommand(cmdstring,con);
//cmd.Parameters.AddWithValue("#id",id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//da.Fill(ds, "customers");
//dataGridView1.DataSource = ds.Tables["customers"];
con.Open();
SqlDataReader red = cmd.ExecuteReader();
con.Close();
dataGridView1.DataSource = red;
button = new DataGridViewButtonColumn();
button.HeaderText = "edit";
button.Tag = ds.Tables["customers"].Columns["customer_id"];
dataGridView1.Columns.Add(button);
}
you could always make a DataBase Class and if you need to refactor this Class to pass in Connection String or read Connection string from .Config File you can use this as a template to get started plus it's a lot cleaner
Notice that I am returning a DataTable you can use this if you like just a suggestion
public class ClassDataManagement
{
public DataTable GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
if you want to use DataSet instead of DataTable replace where i have DataTable with
or change the method to return a DataSet like this below
public DataSet GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
after returning the ds you will need to bind it like this
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
I'm fairly certain that you're not getting any data because you're closing the connection before binding, and because you're using an incompatible type as your data source:
con.Close();
dataGridView1.DataSource = red;
Set the data source prior to closing the connection, or at least be sure to populate the data (for data readers, the data are populated as you enumerate). Additionally, DataGridView.DataSource indicates that it must use one of four interfaces: IList, IListSource, IBindingList, and IBindingListSource. SqlDataReader does not support these. I recommend reading DataAdapters and DataReaders, as this outlines some of the features that are for populating this kind of control.
i have a grid view that is filled through a data-source from the code behind :
protected void Page_Load(object sender, EventArgs e)
{
// filling the grid view
MainGrid.DataSource = Update();
MainGrid.DataBind();
}
protected DataSet Update()
{
SqlConnection conn = new SqlConnection(#"ConnectionString");
SqlCommand cmd = new SqlCommand("SELECT tim,com,pic FROM ten", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
but i have a file upload that inserts the file-path into the database (and it works fine), but i would like to know how to change the column type to image through the code-behind.
thanks
The answer is - from the comments - set your column types in the declaration of the grid, and bind your data in the code behind.
If you need variable column types, the simplest route is to include multiple columns, and show and hide them appropriately.
You need to dispose all the disposable objects using the Dispose()....or like
using (SqlConnection conn = new SqlConnection(#"ConnectionString"))
{
using (SqlCommand cmd = new SqlCommand("SELECT tim,com,pic FROM ten", conn))
{
conn.Open();
using (DataSet ds = new DataSet())
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
MainGrid.DataSource = ds;
}
}
conn.Close();
}
}