DataSet is not updated in visual studio 2010 - c#

I am new to visual studio-2010. I am trying to create an application which reads data from sql database and shows on datagrid. I implemented the code which I found on internet.
here is the sql_button_Click function
private void sql_button_Click(object sender, RoutedEventArgs e)
{
string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\jakkulv\\Downloads\\VS projects\\employee\\employee\\SampleDatabase.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
string SQL = "select emp_id,first_name from employee";
SqlConnection conn = new SqlConnection(ConnectionString);
// open the connection
conn.Open();
//Create a SqlDataAdapter object
SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
// Call DataAdapter's Fill method to fill data from the
// Data Adapter to the DataSet
DataSet ds = new DataSet("employee"); //database table name is "employee"
ds.Clear();
adapter.Fill(ds);
// Bind data set to a DataGrid control
dataGrid1.ItemsSource = ds.DefaultViewManager;
if (ds.HasChanges(DataRowState.Added))
{
// New rows have been added to the dataset, add appropriate code.
MessageBox.Show("data set has changes");
}
else
{
MessageBox.Show("data set has no changes");
// No new rows have been added to the dataset, add appropriate code.
}
but when I execute the same it is showing the message box saying - "data set has no changes".
why dataset is not updated??How to update it??

Your code will always result in the message box with data set has no changes, since it doesn't have any changes.
The data is the same as when it comes from the database, and since you haven't modified it, removed any records or added any records, there are no changes.
Just as the MSDN docs say
Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows.
Try to modify it, and then call ds.HasChanges() and you'll see that it will return true.

Related

How to Connect DataGridView in C# To an SQL Database?

I'm trying to pass data from DataGridView to a Database SqlClient I opened especially for this. When the program runs, it tells me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I made a form with 2 buttons, one for adding data to the DataGridView (works fine) and another one to pass the data to a database table.
the not working button's code is this:
private void button3_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=.;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "SELECT * FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
con.Open();
dataadapter.Fill(ds, "Authors_table");
con.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
What can I do to fix it?
I tried choosing a data source to the DataGridView but it still didn't work out.
Thanks in advance!

Updating Database When Dataset Filled from View (not table)

Background: I have a Windows Forms Application with a DataGridView control that is bound to a DataSet. The DataSet is filled with data from a database view. Some of the DataGridView cells are editable, and rows need to be delete-able.
Problem: When a value in the grid is edited, how do I update the database? It does not appear to be nearly as easy as it would be if it were pointing to a database table, rather than a view. Should I be adding the tables relevant to the view to the DataSet as well, and then making the appropriate changes to the tables and then calling the update DataSet method?
Edit1: I think DataSets that point to a view with joins cannot have the Update() method called.
Edit2: With the below code, I get an error saying:
there is no definition for Update
when my DataSet looks at a view. However, if a DataSet points to a table, Update does exist. Both DataSet are autogenerated by VS. What am I doing wrong?
try
{
this.ASSIGNMENTS_VWTableAdapter.Update(this.TEST_Dataset.ASSIGNMENTS_VW);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Edit3: The following code is what I used to try the SqlCommandBuilder. I get the error I mentioned in my comment below "Dynamic SQL generation is not supported against multiple base tables."
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT * FROM ASSIGNMENTS_VW", connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
builder.GetUpdateCommand();
adapter.Update(tEST_ASSIGNMENTS_VW, "ASSIGNMENTS_VW");
}

Displaying data from local SQL Server CE database in a gridview C#

I am working on a small application for personal use. It is about keeping some data readily available for me.
It just consists of a local database, functions to add, erase or modify 4 or 5 columns of data and displaying the table in a datagridview.
I have managed to add data to the table and I have managed to use a
SELECT * FROM mytable
statement to get the data and iterate through it but I want to bind the table to the datagridview.
Here is my current method of trying to bind the data:
private void button2_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM myTable";
SqlCeConnection conn = new SqlCeConnection(conString);
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, conn))
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
When I run this code it does not throw an exception and if I change the name of the table to something that does not exists then it causes an exception telling that the table does not exists so I know that it is fetching my table. It simply is not showing it.
Any ideas?
Thanks

Sqldataapter advice

At present i have a the following code populating a datagridview showing the user account information on our system. What i want to do do is have a checkbox on the datagridview for the option "accountenabled" and a update button at the bottom of the form so it will update all users that have had changes made against them. I am currently pulling the data back using an sqldatareader however from what i have read i need to use a sqldataadapter. I`ve created the column names on the datagridview and the reader is currently pulling everything back correctly.
Could someone please point me in the right direction of doing this with an sqldatadapter?
Thanks
public UserAdmin()
{
InitializeComponent();
//Load user list
// Locals
Functionality func = new Functionality();
SqlConnection supportDB = null;
SqlCommand CheckUser = null;
SqlDataReader rdr;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string User = System.Environment.UserName.ToString();
string spName = "gssp_ShowAllUsers";
try
{
using (supportDB = new SqlConnection(GSCoreFunc.ConnectionDetails.getConnectionString(ConnectionType.SupportDB)))
{
using (CheckUser = new SqlCommand(spName, supportDB))
{
// Set the command type
CheckUser.CommandType = CommandType.StoredProcedure;
// Populate the parameters.
CheckUser.Parameters.Add(func.CreateParameter("#spErrorID", SqlDbType.Int, ParameterDirection.Output, DBNull.Value));
// Open the connection and populate the reader with the SP output
supportDB.Open();
rdr = CheckUser.ExecuteReader();
if (CheckUser.Parameters["#spErrorID"].Value != null)
{
throw new InvalidOperationException();
}
// If the data reader has rows display output on label
if (rdr.HasRows)
{
//Output values
while (rdr.Read())
{
//Bind to data table
dgvUsers.Rows.Add(rdr["agentID"].ToString(), rdr["createdon"].ToString(), rdr["firstname"].ToString(), rdr["lastname"].ToString(), rdr["username"].ToString(), rdr["emailaddress"].ToString(), rdr["Departments"].ToString(), rdr["accountenabled"].ToString(), rdr["AgentAccountLevel"].ToString());
}
}
// Close reader and connection.
rdr.Close();
supportDB.Close();
}
}
}
catch (Exception ex)
{
//Show error message
string error = ex.ToString(); //Real error
string FriendlyError = "There has been error loading the user list"; // Error user will see
GSCoreFunc.ShowMessageBox.msgBoxErrorShow(FriendlyError);
//Log error to ExceptionDB
GSCoreFunc.ReportException.reportEx(GSCoreFunc.ApplicationInformation.ApplicationName, error, FriendlyError, GSCoreFunc.ApplicationInformation.ComputerName, GSCoreFunc.ApplicationInformation.OperatingSystem, GSCoreFunc.ApplicationInformation.screenSize, GSCoreFunc.ApplicationInformation.IPAdddress, GSCoreFunc.ApplicationInformation.domainName);// Pass error to GSCoreFunc to log to the ExceptionDB
}
}
private void btClose_Click(object sender, EventArgs e)
{
//Close window
Close();
}
}
}
There is nothing wrong with using the SqlDataReader. The SqlDataAdapter is a higher level api that allows you to iterate through an SqlDataReader and store a copy of the results in a DataTable or a DataSet. This copy can then be used as the data source for your DataGridView.
One thing I would change with your code would be to use data binding instead of generating each row manually. If you set the DataSource property of the grid to either your SqlDataReader or to a DataTable filled by an SqlDataAdapter and then call the grids DataBind() method the grid should be filled automatically with your data.
To control the columns you would make sure your query only returns the required columns, and you would define the column setup in your aspx-file.
Using data binding is generally an easier and more flexible approach, so you should consider using that instead.
Look at this code
Initialize a sql adapter and fill with data source . Use a connection string other than using sql data source because it would be easy for customizing. :)

WinForms DataGridView - update database

I know this is a basic function of the DataGridView, but for some reason, I just can't get it to work. I just want the DataGridView on my Windows form to submit any changes made to it to the database when the user clicks the "Save" button.
I populate the DataGridView according to a function triggered by a user selection in a DropDownList as follows:
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife], rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix] FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con);
DataSet ruleTableDS = new DataSet();
ruleTableDA.Fill(ruleTableDS);
RuleTable.DataSource = ruleTableDS.Tables[0];
}
In my save function, I basically have the following (I've trimmed out some of the code around it to get to the point):
using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife],
rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
DataTable dt = new DataTable();
dt = RuleTable.DataSource as DataTable;
ruleTableDA.Fill(dt);
ruleTableDA.Update(dt);
}
Okay, so I edited the code to do the following: build the commands, create a DataTable based on the DataGridView (RuleTable), fill the DataAdapter with the DataTable, and update the database. Now ruleTableDA.Update(dt) is throwing the exception "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records."
I believe there are a few problems here:
The sequence to keep in mind is that when you load up your grid, it is pointed to a datatable/set already.
When you type into the grid, the changes are temporarily persisted to the data table that is bound to the grid. Therefore, you do not want to be creating a data table every time you save, because the changes that were made to the existing data table are being ignored.
Second issue is that you probably don't need to create a binding source everytime, because just like the first point, if the grid is showing data, there is already a binding source that it is bound to.
Third problem is that the SQLCommandBuilder class has methods like GetInsertCommand, GetUpdateCommand, etc. that must be used to actually get the appropriate commands.
using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife],
rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
DataTable dt = new DataTable();
dt = RuleTable.DataSource as DataTable;
//ruleTableDA.Fill(dt);
ruleTableDA.Update(dt);
}
MSDN documentation states that the update/delete/insert commands are automatically set when you manually set the SelectCommand. It doesn't mention that it does the same when you construct one with a SqlDataAdapter. Try adding these lines after creating your SqlCommanduBuilder.
ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand()
ruleTableDA.InsertCommand = commandBuilder.GetInsertCommand()
ruleTableDA.DeleteCommand = commandBuilder.GetDeleteCommand()
You may need this to get the Update Command
ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand();

Categories