Oracle database table in gridview - c#

I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)

You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}

Related

update command C# DataGridView to SQL

I'm attempting to update a SQL table from C# project datagridview "Work_Table". However when I attempt to make the update I get this error
"Update unable to find TableMapping ['Work_Table'] or DataTable 'Work_Table'"
Any ideas?
Here is my code below:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = #"Select * from person.addresstype";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Update(ds, "Work_Table");
MessageBox.Show("Saved");
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
You need to retrieve the DataTable from the .DataSource property of the grid. This will have the information on what was added, updated and deleted.
You can skip the command and pass the select string and connection string directly to the DataAdapter constructor.
Create a CommandBuilder to provide the Insert, Update and Delete text for the DataAdapter.Update. Pass the DataAdapter to the constructor of the CommandBuilder.
private string connString = "Your connection string";
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
try
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter("Select * from person.addresstype", connString))
using (SqlCommandBuilder cb = new SqlCommandBuilder(dAdapter))
{
dAdapter.Update(dt);
}
MessageBox.Show("Saved");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}

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;
}

Getting output from return type DataSet and displaying it in a Gridview

I am trying to get the output from a method with return type as DataSet and using it in a GridView but the output is not reflecting.
Can anyone please advice how to get the output.
public DataSet GetData()
{
try
{
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet output = new DataSet();
adapter.Fill(output);
conn.Close();
return (output);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
}
Home home = new Home();
Output=home.GetData();
GridViewOutput.DataSource = Output.Tables["Out"];
GridViewOutput.DataBind();
Try moving where you declared output and returned it, to as shown bellow.
I changed the part where you declare the grid views data source. You should be able to just declare the datasets datasource as the method itself.
Have a look at this thread on dataset vs datatable Datatable vs Dataset
A DataSet can hold multiple tables. However if you're just returning a single results set a DataTable rather than a DataSet would probably make more sense.
Just change the Methods type to a DataTable. Declare it's source the same way as shown bellow.
public DataSet GetData()
{
//Move where you declare output ot here
DataSet output = new DataSet();
try
{
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(output);
conn.Close();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
//And move the return to here
return output;
}
//Should just need this to display the data
GridViewOutput.DataSource = GetData();
GridViewOutput.DataBind();
One final thing when using SQL in c# I tend to use the using statement. It makes the code a lot cleaner and handles the disposing of resources for you see When should I use the using Statement? . Your code would look like this if you choose to use it:
public DataTable GetData()
{
//Move where you declare output ot here
var output = new DataTable();
using (var conn = new SqlConnection())
{
try
{
conn.ConnectionString = //Your DataBase Connection;
String sql = "Select top 100 * from SEQUENCE";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.commandType = commandType.Text;
Var adapter = new SqlDataAdapter(cmd);
adapter.Fill(output);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", ex.Message, true);
return (null);
}
//And move the return to here
return output;
}
}
//Should just need this to display the data
GridViewOutput.DataSource = GetData();
GridViewOutput.DataBind();

How I Reload Datagridview data while insert or update data in .net form application and database is in access database?

I have a desktop application project. In entry page a datagridview shows the existing items in database. Now when I entry new Item I want to insert it directly in datagridview. That mean I want to reload/refresh datagridview. My database is in MS Access.
private DataTable GetData()
{
DataTable dt = new DataTable();
//using (SqlConnection con = new SqlConnection(conn))
using (OleDbConnection con=new OleDbConnection(conn))
{
OleDbCommand cmd = new OleDbCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
//SqlCommand cmd = new SqlCommand("Select ID,Name from GroupDetails where comID='" + label1.Text + "'", con);
con.Open();
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
dt = ds.Tables[0];
return dt;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//SqlConnection con = new SqlConnection(conn);
OleDbConnection con = new OleDbConnection(conn);
con.Open();
//SqlCommand cmd;
try
{
string query = "insert into GroupDetails (ID,Name) values(#ID,#Name)";
// cmd = new SqlCommand(query,con);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#ID",txtID.Text);
cmd.Parameters.AddWithValue("#Name",txtName.Text);
int i = cmd.ExecuteNonQuery();
if(i!=0)
{
dataGridGroup.DataSource = GetData();
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
con.Close();
}
}
[Note: When I use sql database then it works fine.]
The dbDataAdapterClass (the one that OleDbDataAdapter inherits from) has a SelectCommand, UpdateCommand and InsertCommand. These are responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.
so fulfill the requirements, adding an update command to the adapter.
dataadapter = new OleDbDataAdapter(sql, connection);
Add below code after above line, OleDbCommandBuilder will generate commands for you.
OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);
This tutorial should help you out.

Query Multiple Databases SQL Server

I'm having a problem running a query across multiple databases on an Azure SQL Server. This is the function I have made to return a DataTable from the query once it has been executed. The function takes the database name as a string and inserts it into the conenction string, along with the query to be executed.
The function works fine when I run it once, returning the DataTable populated with returned rows as intended, but when I call the function using a 'foreach' statement (Iterating through a list of database names) I get a timeout error or a login failed error.
Any help on this would be appreciated.
public static DataTable runQuery(String db, String query)
{
using (SqlConnection con = new SqlConnection("Data Source=server.database.windows.net;Initial Catalog=" + db + ";User ID=user#server;Password=password"))
{
con.Open();
using (DataTable dt = new DataTable())
{
try
{
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.Dispose();
da.Dispose();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
}
}
Add cmd.CommandTimeout = 0
try
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandTimeout = 0;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtt);
cmd.Dispose();
da.Dispose();
}
I think you should try adding System.Threading.Thread.Sleep inside the foreach block.

Categories

Resources