SqlDataAdapter is not updating datatable in the database - c#

I'm trying to update datatable in the database using a SqlDataAdapter. I don't see any errors and also it's not updating the database.
I tried other solutions in the stackoverflow but still no luck. Here is my code:
public void Update(DataTable dt, String tableName)
{
try
{
SqlDataAdapter da = new SqlDataAdapter();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
da.SelectCommand = new SqlCommand("SELECT * FROM " + tableName, connection);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.UpdateCommand = cmdBuilder.GetUpdateCommand(true);
da.AcceptChangesDuringUpdate = true;
int res = da.Update(dt);
}
}
catch (Exception oEx)
{
System.Diagnostics.Debug.WriteLine("Ex: " + oEx);
}
}
Thanks in advance for your help!

Related

Executing a query i got Two different results PhpMyAdmin and C#

Hello if i execute the following query in PhpMyAdmin i have 5 Result.
If i execute the exactly query into C# i get back only 1 Result.
I have been beating my head against the table for 2 days but I can't find the solution.
Some ideas?
SELECT
tbl_orders.Data_payment,
tbl_customers.City,
tbl_customers.Country,
tbl_orders.Price,
tbl_orders.state_order,
tbl_products.Product_ID,
tbl_products.Name
FROM
tbl_orders
INNER JOIN
tbl_customers ON tbl_orders.fk_customer_id = tbl_customers.Customer_ID
INNER JOIN
tbl_products ON tbl_orders.fk_product_id = tbl_products.Product_ID
WHERE
tbl_products.Product_ID = '2'
AND tbl_customers.Country = 'Russia'
AND tbl_orders.Data_payment BETWEEN '2019-04-01' AND '2020-04-01'
private void test_load(string query)
{ DataTable dt = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
conn.Open();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
dt.Load(dr);
MessageBox.Show(dt.Rows.Count.ToString());
dataGridView1.DataSource = dt;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("err test_load " + ex);
}
}
After adding the database and testing the code you provided, I find that I still
can not reproduce your problem. I can get the same result in sql-query and in c# code.
You can see the following picture.
I also tested it, I find it is different from your picture.
Ok so i finally solve the problem.
This pice of code in not working it return only one row and should return more than one.
private DataTable test2_load(string query)
{
DataTable dt = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(MyConString))
{
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
conn.Open();
using (MySqlDataReader data_reader = cmd.ExecuteReader())
{
dt.Load(data_reader);
}
}
}
return dt;
}
catch (Exception ex)
{
MessageBox.Show("err test_load " + ex);
return null;
}
}
This is working. It return the right number of rows
private void test3_load(string query)
{
MySqlConnection mysqlCon = new
MySqlConnection(MyConString);
mysqlCon.Open();
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand(query, mysqlCon);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}

SqlDataAdapter handle error - object is not created

I have this error:
Invalid object name 'sap.AfdelingsrapportACTUAL'.
Which is because this table is not created yet.
I need to implement a check in my SqlDataAdapter - so if is null or doesnt get anything it moves on. But i really doesnt know how to.
I think it should be around my SqlDataAdapter but i could be wrong
Code
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(sqldt);
}
What i think it should look like:
public static bool CompareDataTables(DataTable dt, string table, string connectionString)
{
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
if (da == "doesnt have any table")
{
return true;
}
else
{
da.Fill(sqldt);
}
}
int sqlCols = sqldt.Columns.Count;
int excelCols = dt.Columns.Count;
if (excelCols == sqlCols)
{
return false;
}
else return true;
}
One way would be first check for the existence of the data table.
follow the sample given here:
Check if table exists in SQL Server

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

Gridview not binding and showing datas from my database

well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
You must fill the DataSet with data like this :
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();
You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.
using (MySqlConnection con = new MySqlConnection(""))
{
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
DataTable dt = new DataTable();
using (MySqlDataReader reader1 = cmd.ExecuteReader())
{
dt.Load(reader1);
}
GridView1.DataSource = dt ;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);

Categories

Resources