Update typed DataSet is not committed - c#

I have code like this:
int selectedRow = dataGridView1.CurrentCell.RowIndex;
productds.Products[selectedRow].ItemArray = row.ItemArray;
// 1
ProductsTableAdapter padapter = new ProductsTableAdapter();
con.Open();
padapter.Update(productds.Products);
productds.Products.AcceptChanges();
adapter = new OleDbDataAdapter("SELECT * FROM Products ", con);
productds = new ProductDS();
adapter.Fill(productds, "products");
// 2
con.Close();
Here, where 1 is written I can see productds is changed so I can update it, but when I fill productds from db I can see there is no change. What should I do to commit changes to database? Database used is a .mdb file (MS Access).
Init method looks like this
con = new OleDbConnection("PROVIDER = MICROSOFT.JET.OLEDB.4.0; DATA SOURCE = C:\\Users\\me\\Downloads\\NWIND.MDB");
adapter = new OleDbDataAdapter("SELECT * FROM Products", con);
productds = new ProductDS();
adapter.Fill(productds, "products");
dataGridView1.DataSource = productds.Products;
con.Close();

Related

dataset relation in c# for two columns

I would really appreciate a help in this code. I have a DataSet with two tables; I need to create a relation based on two columns as primary key:
public DataSet GetAll()
{
string sql = $#"SELECT * FROM Journal ORDER BY JvNO, cYear;
SELECT * FROM JournalDetail ORDER BY JvNO, cYear";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("Journal_Batch", new DataColumn[] { ds.Tables[0].Columns["JvNO"], ds.Tables[0].Columns["cYear"] },
new DataColumn[] { ds.Tables[1].Columns["JvNO"], ds.Tables[1].Columns["cYear"] });
return ds;
}
}
Currently, I'm doing it like this and it's working but I need it with DataSet relation:
public DataSet GetJournalByID(int JVNO, int cYear)
{
string sql = $#"SELECT * FROM Journal WHERE JvNO = { JVNO } and cYear = { cYear };
SELECT * FROM JournalDetail WHERE JvNO = { JVNO } and cYear = { cYear };";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
I don't know what's wrong with first code, as it returns all matching JvNO or Year.
i want to use the first one to fill two grids as follow:
private void GetData()
{
DataSet currentDs = new DataSet();
grdJournalDetails.DataSource = null;
grdJournal.DataSource = null;
JournalConnector journalConnection = new JournalConnector();
currentDs = journalConnection.GetAll();
grdJournal.DataSource = currentDs.Tables[0];
grdJournalDetails.DataSource = currentDs.Tables[1];
}
then with each row selected from grdJournal to display grdJournalDetails with related data without calling each time the second snippet of code.
i used Dapper and i'm familiar with it, but with devexpress grid, it have to be a datatable to use the event gvJournal_FocusedRowChanged, otherwise datarow returns always null;
Thanks for any suggestion.

How to read memo data from ms access using c#

I have a table in MS Access where few columns are memo datatype.Using c# code, I am reading data from that table and creating a list.That list i am binding with a datagridview.I am able to read the data from each row of the ms access table rows but whereever large data is available it it unable to read the complete data. Any suggestion please?
Here is the code what i am trying. It's getting the data, but for each cell few data only reading, not all:
List<RavasCustomOptional> lstAllAccessories = new List<RavasCustomOptional>();
using (OleDbConnection cn = new OleDbConnection(connectionstring))
{
OleDbCommand cmd = new OleDbCommand(query, cn);
cn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
RavasCustomOptional aRavasOptional = new RavasCustomOptional();
aRavasOptional.OptionalId = Convert.ToInt32(dr["pk_aid"].ToString().Substring(1));
aRavasOptional.OptionalCustomId = dr["pk_aid"].ToString();
aRavasOptional.OptionalMake = dr["c_make"].ToString();
aRavasOptional.OptionalName = dr["c_nam"].ToString();
aRavasOptional.OptionalDescription = dr["c_des"].ToString();
aRavasOptional.OptionalPrice = dr["c_pri"].ToString();
string optionalOtherDescription = dr["OtherDesc"].ToString();
aRavasOptional.OptionalOtherDescription = optionalOtherDescription.Replace("•", Environment.NewLine + "• ");
aRavasOptional.OptionalRemark = dr["c_remark"].ToString();
aRavasOptional.OptionalForProductId = dr["c_pid"].ToString();
aRavasOptional.OptionalForProductModel = dr["c_mod"].ToString();
lstAllAccessories.Add(aRavasOptional);
}
}
}

Show data in datagridview filtered by current date C#

i have large number of rows in my database. when i tried to load all the data in to datagridview it getting stuck. i want to load data to datagridview that only related datetimepicker date. this is my current code
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=uwadminview;port=3306;password=*****************;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from waq115.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conwaqDatabase.Close();
}
then soon after i call this i again use a rowfilter event like this
private void filterdata()
{
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("Convert(submittimestamp, System.String) LIKE '%{0}%'", adminviewDTP.Text);
dataGridView1.DataSource = DV;
}
but in this method performance is very bad when loading more than 9000 rows it getting stuck all the time. i want to method that directly query data from database only related to today
(users are daily update the database and they are insert more than 500 rows each day)
(application still in a testing progress)
(i'm using mysql database)
can someone show me any efficient way to do this)
MySqlCommand cmdwaqDatabase = new MySqlCommand("SELECT * FROM waq115.loans WHERE DATE(submittimestamp) = DATE(NOW())", conwaqDatabase);
UPDATE:
With parameter:
MySqlCommand cmdwaqDatabase = new MySqlCommand("SELECT * FROM waq115.loans WHERE DATE(submittimestamp) = DATE(#p)", conwaqDatabase);
then you can add the parameter like below
cmdwaqDatabase.Parameters.AddWithValue("#P", dateTimeValue); // convert datetime picker value to DateTime and set as the value;
or
cmdwaqDatabase.Parameters.Add(new MySqlParameter("#P", MySqlDbType.Timestamp)).Value = dateTimeValue;
Filter in the database tier instead of the middle tier.
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase =
new MySqlCommand("select * from waq115.loans where submittimestamp = #date; ", conwaqDatabase);
var dateParam = new MySqlParameter();
dateParam.Name = "#date";
dateParam.Value = Convert.ToDateTime(adminviewDTP.Text);
cmdwaqDatabase.Parameters.Add(dateParam);

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.

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