database not affected by dataset after renewing a table - c#

I have a dataset that contains a table. This table has just a column (without primary key). My table is shown in a datagridview. Now, I want to edit data of table. So, I store data of table in a DataTable and then, I clear all data of table in dataset and fill it by DataTable, like this:
DataView dv = ((BindingSource)tblMyTableDataGridView.DataSource).SyncRoot as DataView;
DataTable dt = dv.ToTable();
IDataReader dr = dt.CreateDataReader();
myDataSet.tblMyTable.Clear();
myDataSet.tblMyTable.Load(dr);
By breaking point, that specified that tblMyTable has changed truely.
But it not affected on database. My code is:
tableAdapterManager.tblMyTableTableAdapter.Update(myDataSet.tblMyTable);
tableAdapterManager.UpdateAll(myDataSet);
What is wrong?!?!?
Thanks.

Related

More efficient delete of Sql table from DataTable by identifier

I have to insert-delete a Sql table using a C# DataTable. My two strategies are
delete one row at a time, or
throw the DataTable into a stored procedure and do delete where exists.
Neither strategy is preferred to me as #1 is inefficient and #2 requires some setting up (user schemas, stored procedure, etc.).
Is there another (better) way?
//place buy_detail_id into distinct datatable
DataView view = new DataView(table);
DataTable distinctIds = view.ToTable(true, "buy_detail_id");
//strategey 1: delete one row at a time by Id
foreach (DataRow row in distinctIds.Rows)
{
//delete one row at a time
DeleteRow(row[0]);
}
//strategy 2: throw DataTable into a stored proc as parameter
//then delete where buy_detail_id exists in distinctIds

How to Populate the unbounded datagridview from SQL Server database in C#?

In My Project I'm Using Unbounded datagridview with 33 columns for storing the user data in database and I need to populate the datagridview after each and every Insert, Update and Delete.
My Problem is while populating the datagridview with sql server query it shows the column header repeated with data.
my code is given below :
Private Void PopulateGrid()
{
cs.open();
sqladpter da= new sqlcommand("Select * from Customer",cs);
DataTable dt =new datatable();
da.fill(dt);
datagridview.datasource=dt;
datagridview.Refresh();
}
I'll Call This method at the End Of each and every Insert, Update and Delete.
How about Using something simple like datasource and you can have all your CRUD operations
http://msdn.microsoft.com/en-CA/library/dz12d98w(v=vs.100).aspx
try setting DataSource = null before setting new DataSource
datagridview.DataSource = null;
datagridview.DataSource = dt;

Return Multiple DataTable in C# 2005

I have table1 and table2 in a class..
public DataTable sampletable (DataTable table1,DataTable table2)
{
// How to return the two table(table1 and table2)
}
Advance thank you
public DataTable[] sampletable (DataTable table1,DataTable table2)
{
return new DataTable[] { table1, table2 };
}
Use an array. And to retrieve a particular table:
DataTable[] dtArray = sampletable (YourFirstDt, YourSecondDt);
DataTable table1 = dtArray[0];
DataTable table2 = dtArray[1];
Assuming they have the same schema, you can use the DataTable.Merge Method
public DataTable sampletable(DataTable table1, DataTable table2)
{
table1.Merge(table2);
return table1;
}
The Merge method is used to merge two DataTable objects that have
largely similar schemas. A merge is typically used on a client
application to incorporate the latest changes from a data source into
an existing DataTable. This allows the client application to have a
refreshed DataTable with the latest data from the data source.
The merge operation takes into account only the original table, and the
table to be merged. Child tables are not affected or included. If a
table has one or more child tables, defined as part of a relationship,
each child table must be merged individually.
When merging a new source DataTable into the target, any source rows
with a DataRowState value of Unchanged, Modified, or Deleted, is
matched to target rows with the same primary key values. Source rows
with a DataRowState value of Added are matched to new target rows with
the same primary key values as the new source rows.
You can use DataSet , Create a new DataSet and Add the multiple tables to it ,
For Eg-
DataSet Ds = new DataSet();
DataTable Dt1= new DataTable();
Ds.Tables.Add(Dt1)
you can add multiple tables and to access the datatable you can use the index ( eg -
Ds.Tables[0])
Hope this answers your question!!.
public DataSet Getdatasettables()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
return ds;
}

How to replace a DataBase Table by a DataTable

I am trying to replace a Table (FooTable) in my DataSource (an SQL CE Database) by a DataTable (which bind to a DataGrid). The reason I want to do this is: after I populate from a Database to a DataSet (which show all the rows on the DataGrid), I might edit, delete, and add multiple rows to the DataTable. Instead of updating my changes to DataSource (SQL CE) each time I modified the DataTable, I want to do it collectively at the end of the session.
My approach is straight-forward:
`DELETE` all data from my DataSource table (FooTable) (I'm using **SQL CE**, so `TRUNCATE` is not available)
INSERT the `DataTable's` data in to the emptied DataSource Table
Following is my C# code
/* Truncate the DataSource Table */
SqlCeCommand delCmd = new SqlCeCommand("DELETE FROM FooTable", conn)
conn.Open();
delCmd.ExecuteNonQuery();
conn.Close();
/* Insert DataTable into an empty DataSource Table */
string ins = #"INSERT INTO FooTable (FooName) values (#fooName)";
SqlCeCommand cmd = new SqlCeCommand(ins, conn);
da.InsertCommand = cmd;
da.Update(ds, "FooTable");
The codes work if I add or delete rows on the DataTable, but when I edit a specific row on the DataTable and Insert the table to my DataSource, I get the following error
"Update requires a valid UpdateCommand when passed DataRow collection with modified rows."
I do not understand why I get this error. I have already empty all rows in my DataSource table and my DataSource shouldn't not know there are modified rows but insert all DataTable Rows as new rows.
Or, is there a simple way to "REPLACE" a DataSource table by a DataTable?
[EDITED]
I tried setting the RowState manually like below code
foreach (DataRow row in dt.Rows)
{
row.RowState = DataRowState.Added;
}
but RowState is only read only and cannot be written.
[EDITED - 2nd]
I tried setting it using SetAdded()
foreach (DataRow row in dt.Rows)
{
row.SetAdded();
}
Then I get the following error:
"SetAdded and SetModified can only be called on DataRows with Unchanged DataRowState."
Still not manage to get it to work...
[EDITED - 3rd]
So finally get it to work with the following code:
using (SqlCeCommand insCmd = new SqlCeCommand(#"INSERT INTO FooTable (FooName) VALUES (#fooName)", conn))
{
insCmd.Parameters.Add("#fooName", SqlDbType.NVarChar, 10, "FooName");
dt.AcceptChanges();
foreach (DataRow row in dt.Rows)
{
row.SetAdded();
}
da.InsertCommand = insCmd;
da.Update(ds, "FooTable");
}
The DataTable tracks RowStates internally.
When you modify an existing row, its RowState becomes Modified, so the DataAdapter tries to run an UPDATE command.
You need to call the SetAdded() method on the modified rows to set their RowStates to Added rather than Modified.

Inserting just a new record using DataSet (.net c# ado.net )

I've a form containing more than 200 text boxes in .NET desktop application. I want to insert them into their respective 4 tables of Database. Now how should I go about it using Dataset & DataAdapter to do this?
I mean usually this will be the flow:
Populate the DataSet using DataAdapter.Fill(Dataset,"DataTable");
manipuate the data of DataSet
DataAdapter.Update(Dataset,"DataTable") updates the content back to Database.
Code:http://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-intro.html#connector-net-tutorials-data-adapter
But here I just want to insert a new record in 3 different tables.
I think the way is to
Programmatically Create A dataset with 3 Datatables.
Bind 200 Textboxes to respective columns of these Datatabes
dataAdapter.Update(dataSet, dataTable.TableName);
Am I right?
How does dataAdapter.Update(dataSet, dataTable.TableName); work? Because, my each dataTable will have only one record. (the new record that is to be inserted. binded with those 200 TextBoxes of the form) where as the Table of the Database will have thousands of records. If I do dataAdapter.Update(dataSet, dataTable.TableName); will it delete all the rest of the records and insert this one alone?
I just want to insert a new record (without fetching other 1000s of records into my Dataset) into Database.Table using Dataset.
Each row has a RowState Property, this will be used by the dataAdapter. So if your dataset has only one new row, the row state will be DataRowState.Added. The DataAdapter will insert the row and change the row state to DataRowState.Unchanged. All other rows in the database will be unchanged.
IDbTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
foreach (DataTable dataTable in dataSet.Tables)
{
string sql = "SELECT * FROM " + dataTable.TableName + " WHERE 0 = 1";
SqlDataAdapter dataAdapter = new SqlDataAdapter (sql, dbConnection);
dataAdapter.Update(dataSet, dataTable.TableName);
}
}
catch
{
dbTransaction.Rollback();
throw;
}
dbTransaction.Commit();
Remark: Will not work if there are constraints in the database defined.
Simply make the SQL insert commands and execute them:
string cmd="insert into myTable(column1, column2, etc) values (#text1,#text2, etc)";
SqlCommand sqlcmd=new SqlCommand(cmd,mySqlConnection);
sqlcmd.Parameters.Add("#text1",SqlDbType.NChar,textbox1.Text);
sqlcmd.Parameters.Add("#text2",SqlDbType.NChar,textbox2.Text);
sqlcmd.ExecuteNonQuery();

Categories