How to retrieve data from MySQL DB to GridView in ASP - c#

I am using MySQL as DB and I want to retrieve table data to GridView in my browser. Below is the code I am using, there are no errors but if I run the page, it shows blank
MySqlConnection myconn = new MySqlConnection("server=localhost;user id=;password=;database=workers;");
string strSQL = "select * from details";
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(mydata);
DataSet ds = new DataSet();
mydata.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myconn.Close();
I have tried with Microsoft SQL Server DB by adding DB file and same content in DB, then it worked.

you did not open your connections. try it by adding this
myconn.open();
before this line
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);

open your database connections

Related

Fill DataTable from Oracle Database Table - C#

I have successfully built connection string and able to populate table data when the database is Access as:
DataTable results = new DataTable();
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
OleDbCommand cmd = new OleDbCommand("SELECT * from TABLE_A", thisConnection); //EDIT : change table name for Oracle
thisConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
I am new to Oracle though. Can somebody mention what changes to make in above code for Oracle database?
You can try this;
OracleConnection conn = new OracleConnection("Your Connection string");
//Open the connection to the database
conn.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("your select query");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}

How to add a column when using SqlDataAdapter to fill a datagridview

I am using SQL to fill my datagridview. I am doing that this way:
string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cn);
string sql = "some text here";
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
Now it deletes the old datagridview and paste the selection. But I want just to add the data to the column right of the existing data.
Thanks in advance
This requirement sounds like it could be met with a SQL Inner Join in the query you're using in your SqlDataAdapter. If you were able to join your two data sources together on matching keys, you could simply pull the data down once. But I'm going to assume there's some reason why that won't work for you.
You can in fact do what you want with a DataSet, but you'll need to take a few more steps:
string sql = "The first query"
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
// I don't know what your primary key is, but you need to have one.
// I am assuming it's called "author_id".
DataColumn authorIdColumn = ds.Tables["Authors_table"].Columns["author_id"];
ds.Tables["Authors_table"].PrimaryKey = new[] { authorIdColumn };
// Get your second set of data
sql = "My second query, which also has the same primary key, but has more columns"
dataadapter = new SqlDataAdapter(sql, myConnection);
dataadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet ds2 = ds.Clone();
myConnection.Open();
dataadapter.Fill(ds2, "Authors_table");
myConnection.Close();
// Now we use the DataSet.Merge method, which is very powerful.
ds.Merge(ds2, false, MissingSchemaAction.AddWithKey);
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
You may have to experiment with that a lot: this is just the outline. Without knowing your data and what you do up to this point, it's hard to know what settings or methods you might also need to call.
Try this. I ran multiple queries in one go
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM Customers; SELECT * FROM Orders", connection);
adapter.TableMappings.Add("Table", "Customer");
adapter.TableMappings.Add("Table1", "Order");
adapter.Fill(ds);

Passing Datagridview to dataset

Hello internet so first i am newbie at c# and i am doing project about changing data from a sql table. I passed the result of the query to the datatable and datagridview, but what i want next is i want the modified datagridview table passing to a dataset. this is how i get my table from the sql:
string query = "select Article,Barcode,\"Minimum Stock\",\"Current Stock\" from article where Fid=2 and \"Minimum Stock\" > \"Current Stock\"";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
da.Dispose();
Now the users will modifie the table and valid the information. How can i save it to a dataset?
I tried to bind dataset to the datagridview:
Dataset1.Tables.Add(datagridview1.datasource);
But it threw a error where it says datasource doesn't use here
Can anyone help?

Copying a row from one database table to its twin on a different server through C#

I'm trying to design a method to allow me to take a row from a SQL database using a SELECT. I then want to INSERT the returned row into an identical table on a database which resides on a different server.
My server connection and SELECT statement both work; I can view the row I want copied in a console window.
The issue I'm having is figuring out what data structure I need to use in C#, how to populate this data structure with the SELECT, and finally how to use that data structure to INSERT the row.
I'd like to keep the option for multiple rows open, but for now if I could get a single row transferring across it would be fantastic.
Thank you.
Edit: I've been able to work through this myself after a bunch of research. I've included my code below in the heop it helps someone else, but although it works, it is far from ideal. I am an amateur and it is not yet complete.
static public void CopyDatabaseRows(string ConnectionStringDEV, string ConnectionStringLOCAL, string queryString)
{
//Connect to first database table to retreive row/rows and populate dataset + datatable.
DataSet dataSet = new DataSet();
SqlConnection conn = new SqlConnection(ConnectionStringDEV);
conn.Open();
SqlCommand command = new SqlCommand(queryString, conn);
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, conn);
dataAdapter.FillSchema(dataSet, SchemaType.Mapped);
dataAdapter.Fill(dataSet, "dbo.FileRegister");
dataTable = dataSet.Tables["dbo.FileRegister"];
conn.Close();
//Connect to second Database and Insert row/rows.
SqlConnection conn2 = new SqlConnection(ConnectionStringLOCAL);
conn2.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn2);
bulkCopy.DestinationTableName = "dbo.FileRegister";
bulkCopy.WriteToServer(dataTable);
}
I'd suggest you use something like Simple.Data (https://github.com/markrendle/Simple.Data) to do this really easily. Because it uses C# dynamics, you can just load the dynamic type, and insert it directly into a second Simple.Data connection without worrying about type conversion.
Something like:
var db = Database.OpenConnection("data source=.;initial catalog=Xyz;etc");
var db2 = Database.OpenConnection("data source=somewhereElse;initial catalog=Xyz;etc");
dynamic user = db.Users.FindById(1);
db2.Users.Insert(user);
It works perfectly... I modified this code... Use it...
string local = "Server=destinationservername;Database=destinationserverdb;Uid=sa;Pwd=<Password>;
string dev = "Server=sourceservername;Database=sourceserverdb;Uid=sa;Pwd=Password;
private void btncopy_Click(object sender, EventArgs e)
{
CopyDatabaseRows(dev, local, query);
}
static public void CopyDatabaseRows(string ConnectionStringDEV, string ConnectionStringLOCAL, string queryString)
{
//Connect to first database table to retreive row/rows and populate dataset + datatable.
DataSet dataSet = new DataSet();
SqlConnection conn = new SqlConnection(ConnectionStringDEV);
conn.Open();
SqlCommand command = new SqlCommand(queryString, conn);
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, conn);
dataAdapter.FillSchema(dataSet, SchemaType.Mapped);
dataAdapter.Fill(dataSet, "dbo.DeviceLogs");
dataTable = dataSet.Tables["dbo.DeviceLogs"];
conn.Close();
//Connect to second Database and Insert row/rows.
SqlConnection conn2 = new SqlConnection(ConnectionStringLOCAL);
conn2.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn2);
bulkCopy.DestinationTableName = "dbo.DeviceLogs";
bulkCopy.WriteToServer(dataTable);
MessageBox.Show(dataTable.Rows.Count.ToString() + " rows copied successfully", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Return Null Data

SqlConnection con = new SqlConnection("Data Source=MOSTAFA;Initial Catalog=mohasba;Integrated Security=True");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = con.CreateCommand();
da.SelectCommand.CommandText = "select sum(مدين) AS مدين,sum (دائن) AS دائن from اذن_قيد where اسم_البيان='" + comboBox1.SelectedIndex + "'";
da.Fill(ds, "اذن_قيد");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "اذن_قيد";
When i use this code, it return null data
But When i use this command in sql server "Return Data"
I dont think there is any error with the code above.
What you can try is, First of all make sure that the connection string you are using can access the database.
Secondly, since you are using some kind of language coallation in your sql server queries, make sure that ASP.NET recongnizes the query and sends them to the sql server in the appropiate coallation.
Hope this helps.

Categories

Resources