Unable to insert row to a table using OleDBAdapter - c#

OleDbConnection _connection = new OleDbConnection();
StringBuilder ConnectionString = new StringBuilder("");
ConnectionString.Append(#"Provider=Microsoft.Jet.OLEDB.4.0;");
ConnectionString.Append(#"Extended Properties=Paradox 5.x;");
ConnectionString.Append(#"Data Source=C:\Clients\Rail\Wheelsets;");
_connection.ConnectionString = ConnectionString.ToString();
_connection.Open();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Vehicles;", _connection);
DataSet dsRetrievedData = new DataSet();
da.Fill(dsRetrievedData);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
da.InsertCommand = builder.GetInsertCommand();
////Insert new row
DataRow rowNew = dsRetrievedData.Tables[0].NewRow();
rowNew[dsRetrievedData.Tables[0].Columns[0].ColumnName] = "978";
rowNew[dsRetrievedData.Tables[0].Columns[1].ColumnName] = "222";
rowNew[dsRetrievedData.Tables[0].Columns[4].ColumnName] = "999";
rowNew[dsRetrievedData.Tables[0].Columns[5].ColumnName] = "999";
rowNew[dsRetrievedData.Tables[0].Columns[6].ColumnName] = "999";
dsRetrievedData.Tables[0].Rows.Add(rowNew);
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
int result = da.Update(dsRetrievedData);
thats the code i use. as you can see i have a paradox table. and some how result = 0 at end of it all.
any ideas what is my mistake?
thanks upfront.
-=Noam=-

What is your InsertCommand?
Also try after removing these line
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
if you call AcceptChanges all changes in the datatable is accepted so there is no rows which is changed so there is nothing to update

Remove call to AcceptChanges() :
dsRetrievedData.Tables[0].AcceptChanges();
dsRetrievedData.AcceptChanges();
According to MSDN:
Commits all the changes made to this
DataSet since it was loaded or since
the last time AcceptChanges was
called.
Which means, it marks newly added row as not new.

Related

dataGridView not showing data after DataSource

I am new to C# and have simple method to show data from a table DimCustomer. I am calling this method from a button but its not displaying data. Although when i debug my code i can see data, but not displaying it. Any suggestions please
private void ShowGridData()
{
// create a connection object
string ConnectionString = "Integrated Security=SSPI;" +
"database=AdventureWorksDW2012;" + "server=DESKTOP-L9L3SMT\\SQL2K12;";
SqlConnection conn = new SqlConnection(ConnectionString);
// open the connection
conn.Open();
// Create a DataTableMapping object
DataTableMapping myMapping = new DataTableMapping("DimCustomer", "mapCustomer");
SqlDataAdapter adapter = new SqlDataAdapter("Select * FROM DimCustomer where LastName='yang' and BirthDate='1966-04-08'", conn);
// Call DataAdapter's TableMappings.Add method
adapter.TableMappings.Add(myMapping);
// Create a DataSet object and Call DataAdapter's Fill method
DataSet ds = new DataSet();
adapter.Fill(ds, "DimCustomer");
dataGridView1.ColumnCount = 0;
dataGridView1.DataSource = ds.DefaultViewManager;
}
Can you please try this instead?
dataGridView1.DataSource = ds.Tables[0];

DataTable adding Columns to DataGrid instead of adding new rows?

I have a DataGridView that I'm trying to pull data to from an SQLite database.
The structure of the DataGridView is:
TaskName : String
TaskDueDate : String
Status : ComboBox
Code:
String SelectQuery = "Select TaskName,TaskDue,Status from TASKS Order BY Status";
SQLiteConnection slite = new SQLiteConnection("data source = Dash.sqlite");
slite.Open();
SQLiteDataAdapter data = new SQLiteDataAdapter(SelectQuery, slite);
SQLiteCommandBuilder Command = new SQLiteCommandBuilder(data);
DataTable table = new DataTable();
data.Fill(table);
MyTasksGrid.AutoGenerateColumns = false;
MyTasksGrid.DataSource = table;
I've spent the past few hours on here looking at several question including this one,
however it was producing the exact same results for me as the code above.
This question also suggests my code is correct from the accepted answer?
I get the correct amount of rows showing up in the grid, but all the cells are blank. If I remove the AutoGeneratColumns line it adds the data but in new columns, which I don't want. (I want it to be added in the already defined columns.)
Could anyone give me a hand to see where I am going wrong?
String SelectQuery = "Select ID,TaskName,TaskDue,Status from TASKS Order BY Status";
SQLiteConnection slite = new SQLiteConnection("data source = SupportDash.sqlite");
slite.Open();
SQLiteDataAdapter data = new SQLiteDataAdapter(SelectQuery, slite);
SQLiteCommandBuilder Command = new SQLiteCommandBuilder(data);
var Bind = new BindingSource();
DataTable table = new DataTable();
Bind.DataSource = table;
MyTasksGrid.AutoGenerateColumns = false;
MyTasksGrid.DataSource = table;
MyTasksGrid.DataSource = Bind;
MyTasksGrid.Refresh();
data.Fill(table);
I also needed to add the 'DataPropertyName' in the control properties.

DataAdapter Update issue

The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.

How do I use adapter.Update(table)

string qry="select *from mom";
Dataset dataset= new Dataset();
SqlDataAdapteradap adap= new SqlDataAdapter(qry,con);
adap.Fill(dataset,"MOM");
DataRow drow = dataset.Tables["MOM"].NewRow();
drow[0] = MRefDDL.SelectedItem.Text;
drow[1] = project.Text.Trim();
drow[2] = agendatopic3.Text.Trim();
drow[3] = presenter3.Text.Trim();
drow[4] = discus.Text.Trim();
drow[5] = conclu.Text.Trim();
drow[6] = "1";
dataset.Tables["MOM"].Rows.Add(drow);
adap = new SqlDataAdapter();
adap.Update(dataset, "MOM");
Here I have One Dataset with MOM Table which fill by data adapter
when after add new row into data set. iwant add this row into database
table with help of adapter.update() Method.But its giving me error:-
Update requires a valid InsertCommand when passed DataRow collection
with new rows.
In the dataadapter, there are insert, update and delete queries that you need to add. The wizard can also do that for you. You can also:
adp.InsertCommand = New SqlCommand(sql, connection)
etc.
Look at https://stackoverflow.com/a/21239695/1662973 for more detailed info.
you are reinitializing the dataadapter just before the Update() method. Please comment this.
//adap = new SqlDataAdapter(); // make this line comment
adap.Update(dataset, "MOM");

DataSet, SqlDataAdapter, Multiple select returns one table

I would like to make one call (containing several SELECT statement) to the database and then databind the results to multiple components.
I'm using a DataSet and SqlDataAdapter to fill tables that are then bound to components.
Problem is the results of the first SELECT statement are put into both tables so I get a "'System.Data.DataRowView' does not contain a property..." error when I try to use the second lot of data on the second component.
Have I misunderstood how this is meant to work?
DataSet ds = new DataSet();
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);
StringBuilder topicDropDownListSQL = new StringBuilder();
topicDropDownListSQL.Append("SELECT topic.topic_ID, topic.topic_title FROM FPL2012_TOPIC as topic WHERE topic.topic_isEnabled = 1;");
topicDropDownListSQL.Append("SELECT explain.itemExplanationType_ID, explain.itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE as explain;");
SqlDataAdapter da = new SqlDataAdapter(topicDropDownListSQL.ToString(), connection);
ds.Tables.Add("Topics");
ds.Tables.Add("ExplainType");
ds.EnforceConstraints = false;
ds.Tables["Topics"].BeginLoadData();
da.Fill(ds.Tables[0]);
ds.Tables["Topics"].EndLoadData();
ds.Tables["ExplainType"].BeginLoadData();
da.Fill(ds.Tables[1]);
ds.Tables["ExplainType"].EndLoadData();
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataSource = ds.Tables["Topics"];
topicDropDownList.DataBind();
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataSource = ds.Tables["ExplainType"];
explanationTypeDropDownList.DataBind();
connection.Close();
You can use this acces the tables by there indexes not by there names
DataSet ds = new DataSet();
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myString"].ConnectionString);
String qry="SELECT topic_ID,topic_title FROM FPL2012_TOPIC WHERE topic_isEnabled = 1; SELECT itemExplanationType_ID, itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE ";
SqlDataAdapter da = new SqlDataAdapter(qry, connection);
da.Fill(ds)
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataSource = ds.Tables[0];
topicDropDownList.DataBind();
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataSource = ds.Tables[1];
explanationTypeDropDownList.DataBind();
connection.Close();
OK, I tried using a datareader next, didn't expect it to work but it does! I can make multiple select statements and then fill multiple componenets. I'm not marking this as an answer as I still think it would be useful to know how to do it using the dataset.
The new code that worked for me (in case it is useful):
string connectionString = WebConfigurationManager.ConnectionStrings["myString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
StringBuilder sql = new StringBuilder();
sql.Append("SELECT topic.topic_ID, topic.topic_title FROM FPL2012_TOPIC as topic WHERE topic.topic_isEnabled = 1;");
sql.Append("SELECT explain.itemExplanationType_ID, explain.itemExplanationType_type FROM FPL2012_ITEM_EXPLANATION_TYPE as explain;");
SqlCommand command = new SqlCommand(sql.ToString(), connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
topicDropDownList.DataSource = reader;
topicDropDownList.DataValueField = "topic_ID";
topicDropDownList.DataTextField = "topic_title";
topicDropDownList.DataBind();
reader.NextResult();
explanationTypeDropDownList.DataSource = reader;
explanationTypeDropDownList.DataValueField = "itemExplanationType_ID";
explanationTypeDropDownList.DataTextField = "itemExplanationType_type";
explanationTypeDropDownList.DataBind();
reader.Close();
connection.Close();

Categories