OleDbDataAdapter can't not update the access database - c#

I use OleDbCommand to run the sqlcommand that can update the Access database.
But when I try to use OleDbDataAdapter and DataTable to update the database,
it doesn't work.
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
DataTable table = new DataTable();
adapter.Fill(table);
DataRow row = table.NewRow();
row["k"] = "november";
row["v"] = "eleven";
// table.AcceptChanges();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(table);
// table.AcceptChanges();
return table;
}
When I run the code, the database doesn't change.

This DataRow row = table.NewRow(); creates a row with table shema but doesn't add the row to the DataTable. You need to add the row to the table :
table.Rows.Add(row);
complete code
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from confirm", conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
DataTable table = new DataTable();
adapter.Fill(table);
DataRow row = table.NewRow();
row("k") = "november";
row("v") = "eleven";
//**You missed this**
table.Rows.Add(row);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(table);
// table.AcceptChanges();
return table;
}

Related

Create a row according to empty DataTable Definition

After executing DataAdapter and get an empty DataTable. I need to create a new row according to empty datatable definition. Please help in this point.
SqlConnection con = CreateCon();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Connection = con; da.SelectCommand.CommandText = "spGET_RackZone";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
DataSet ds = new DataSet();
da.Fill(ds);
if (con.State == ConnectionState.Open){
con.Close();
}
DataTable dt = ds.Tables[0];
Now I want to create a row when datatable is empty.
DataTable table = new DataTable();
if(table.Rows.Count==0)
{
DataRow row = table.NewRow();
table.Rows.Add(row);
}
//if you already know the column of the table
table.Columns.Add("sl.No", typeof(int));
table.Columns.Add("Name", typeof(string));
// Here we add a DataRow.
table.Rows.Add(57, "Amin");

DataTable and ODBC adapter

I need to fill DataTable from ODBC Data adapter. I can see that dataTable is still empty but DataSet (ds) is successfully filled with data though.
OdbcConnection cnn;
cnn = new OdbcConnection(azureConnection);
using (OdbcCommand command = cnn.CreateCommand())
{
command.CommandText = "{call sp_Get_Excel_Data(?,?,?,?,?,?,?,?)}";
command.Parameters.AddWithValue("#StartDate", startDate);
command.Parameters.AddWithValue("#EndDate", endDate);
command.Parameters.AddWithValue("#startTime", startTime);
command.Parameters.AddWithValue("#endTime", endTime);
command.Parameters.AddWithValue("#rptSymbol", tickerSymbol);
command.Parameters.AddWithValue("#reg", RegId);
command.Parameters.AddWithValue("#events", events);
command.Parameters.AddWithValue("#userId", userId);
DataTable dataTable = new DataTable();
cnn.Open();
//DataTable
OdbcDataAdapter adapter = new OdbcDataAdapter(command);
adapter.Fill(dataTable);
//DataSet
DataSet ds = new DataSet();
adapter.Fill(ds);
string[] colNames = new string[dataTable.Columns.Count];
int col = 0;
foreach (DataColumn dc in dataTable.Columns)
colNames[col++] = dc.ColumnName;
}
Can you suggest why I can't see data in DataTable and how to make it work?
Ok, I solved the issue by casting to DataTable:
DataTable dataTable = ds.Tables[0];
You can remove
adapter.Fill(dataTable);
And put after filling ds
dataTable = ds.Tables[0]
Or
dataTable = ds.Tables["name_of_your_table"]

Gridview not populating after adding DataKeyNames

I have a gridview that populates from a data table when a button is clicked.
The code goes like this:
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("One", typeof(string)),
new DataColumn("Two", typeof(string)),
new DataColumn("Three",typeof(string)) });
string strConnectionString = ConfigurationManager.ConnectionStrings["---"].ConnectionString;
SqlConnection conn = new SqlConnection(strConnectionString);
using (SqlCommand cmd = new SqlCommand("Select * FROM ---", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
dt.Rows.Add(reader["One"].ToString(), reader["Two"].ToString(), reader["Three"].ToString());
}
conn.Close();
}
GridView2.DataSource = dt;
GridView2.DataBind();
Now whenever i try to add a DataKeyName to the gridview, it would not be populated.
I tried setting it manually and using
GridView2.DataKeyNames = new string[] {"Key"};

Collect data and display the data in a column label

How can I sum a column to the table without dataGridView and i'm using sql command method And my database is in SQL server 2008.
I like this script
using System.Data;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("Select Price from PriceList", connection);
sda.Fill(dt);
int sum=Convert.ToInt32(dt.Compute("sum(Price)",""));
Label1.Text=sum.ToString();
You can loop through the DataTable and sum the field you like.
You can try something like this one,
string query = "SELECT Price FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable dtSource = new DataTable();
dAdapter.Fill(dtSource);
int colSum =0;
foreach (DataRow dr in dtSource .Rows)
{
colSum += Convert.ToInt32(dr["Price"]);
}
TotalValueLabel.Text = colSum.ToString();
For multiplication, you can try something like this,
string query = "SELECT Qty,Price FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable dtSource = new DataTable();
dAdapter.Fill(dtSource);
dtSource.Columns.Add("3rdColumn");
foreach (DataRow dr in dtSource .Rows)
{
dr["3rdColumn"]= Convert.ToInt32(dr["Qty"]) * Convert.ToInt32(dr["Price"]);
}

datagridviewcombobox columns Dependent on another column

How To Do This Work on gridviewcomboboxcolumns any idea plx
//Form Load Event
string query="select article_name from article";
SqlCommmand cmd = new SqlCommand(query,con);
SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
combobox1.items.clear();
for(int i=0;i<dt.rows.count;i++)
{
combobox1.items.add(dt.rows[i].cells[0].toString());
}
\ComboBox1 Selected IndexChange Event
string query1="select description from article where article_name='"+combobox1.selectedItem.ToString()+"'";
SqlCommmand cmd1 = new SqlCommand(query1,con);
SqlDataAdapter da1= new SqlDataAdapter(cmd);
DataTable dt1=new DataTable();
da1.Fill(dt1);
combobox2.items.clear();
for(int i=0;i<dt1.rows.count;i++)
{
combobox2.items.add(dt1.rows[i].cells[0].toString());
}
\Now Assume these 2 combox is gridviewCombobox Columns so how to make
this work on gridviewcombobox columns
Project in Windows Form in C#
I m posting this answer after a few months because its helps for
thoose whoose facing problem on DataGridviewComboboxcell
I did my own skill First Fill my first/Main Column
SqlCommand objCmd = new SqlCommand("select distinct article_name from Setup_article_custominvoice", con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
article.DataSource = dt;
//this column1 will display as text
article.DisplayMember = "article_name";
After that i was going on Cell End Edit
if (dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells["article_name"])
{
string CategoryValue = "";
//string CategoryValue1 = "";
if (dataGridView1.CurrentCell.Value != null)
{
CategoryValue = dataGridView1.CurrentCell.Value.ToString();
//CategoryValue1 = dataGridView1.CurrentCell.Value.ToString();
}
//SqlConnection objCon = new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=dbTest3;Integrated Security=True");
string query = "select article_name,composition from Setup_article_custominvoice where article_name='" + CategoryValue + "'";
SqlCommand objCmd = new SqlCommand(query, con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
DataGridViewComboBoxCell t = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2] as DataGridViewComboBoxCell;
t.DataSource = dt;
t.DisplayMember = "composition";
}

Categories