I am doing some c# and mysql and I was successful at getting mysql data into a grid view for the first time! Now, my main question is, how do I manage the grid view style with this? For example, say I have already created columns and such, how do I put the mysql data into a specific column in the grid view?
Below is the code that is actually loading the data into the grid view.
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("SELECT * FROM `swipes`", conn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
Also, this creates columns based on the mysql data, how do I modify the width of these columns and such, or like stated above, use my own custom columns for my data? I've never done any mysql work in any UI, so I'm open to suggestions and tutorials as well. Thanks in advance!
If you really want to do this (as someone has already stated you should look at other options) you can create the columns in the designer and set the DataGridViewColumn.DataPropertyName on each column to the columns returned by the autogenerated dataset. Remember to turn of autogeneration of columns (AutoGenerateColumns) on the grid. This way you have full control of the column styles.
try this
string connection = "server=localhost;database=adil;user=root;password=";
MySqlConnection con = new MySqlConnection(connection);
con.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = con;
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from studentrec";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Related
I have a MySQL connection in C# that supposedly puts the table data into a DataGridView, but it has a problem and it makes the rows for every account in my users table in my db, but it doesn't show the actual data. Can anyone help?
My code:
public Form1()
{
InitializeComponent();
string connectionString = "Server=mysql.dunkycart.com; Database=dunkycart; Uid=dunkycart; Pwd=rooB-dnK-sqL;"; //Set your MySQL connection string here.
string query = "SELECT name, username, email FROM users"; // set query to fetch data "Select * from tabelname";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
The issue:
Nevermind, I just found a fix. What I had to do is set the DataPropertyName for each column in the DataGridView to the corresponding column in the db table.
Because you are using DataSet instead of DataTable so you need to change this:
adapter.Fill(ds);
To this:
adapter.Fill(ds,"tbl");
Or you can use a DataTable instead of DataSet:
DataTable dt = new DataTable();
adapter.Fill(dt);
Not sure if this question has been asked before, so here goes..
I have a front end app coded in C# windows forms. On a second form i have two datagridviews that gets populated from two different sql server pre-defined views
I need to refresh both datagrids at the same time with a single button click
My button click even looks like this..
private void RefreshBTN_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
How i understand this is, C# opens new connection, queries the DB and returns by filling datagridview1 with the required data. I would like the same click event to request data from another sql view and populate another datagridview at the same time. Visually both grids are aligned vertically on the same form, one on to of the other.
Many thanks in advance
Move the code for refreshing Grid1 into a separate function. Then copy paste and duplicate that function for Grid2. Change the SQL for Grid2 as well as the Grid2 name. Rename the copied function with 2. Then add a call to both functions so your button click will refresh both grids.
private void RefreshBTN_Click(object sender, EventArgs e)
{
//call both functions to refresh both on button click
RefreshGrid1();
RefreshGrid2();
}
private void RefreshGrid1()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
//give this function a unique name to represent the second grid refresh
private void RefreshGrid2()
{
SqlConnection myConnection = new SqlConnection("removed for illustration only");
string query = "select * from daily_orders order by orderno DESC";
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//rename this to your second grid name
dataGridView2.DataSource = dt;
}
So i have a website hosted on blacknight.com. Im coding with cSharp and asp.net I have mySQL database stored within blacknight also.
However I want to add an admin section to my site where a user could log in and press a "load data" button and the registration table values from blacknight database would appear in a grid view.
However its just not working. Im wondering do I have to physically connect my gridview to my database? Because I have tried to connect to my hosted database with my gridview and it keeps saying it cant connect.
Below is the code behind my load data button. As as it stands when I upload my adminpages to blacknight and run, the gridview is not even appearing. This is my Fourth year project for college and I really need to get it working. Any help would be much appreciative.
protected void Button1_Click(object sender, EventArgs e)
{
string constring ="Server=xxxx; Database=xxxx; Uid=xxx; Pwd=xxx";
MySqlConnection conDb1317466_bk = new MySqlConnection(constring);
DataSet dbdataset = new DataSet();
//binding.DataSource = this.bindingSource.DataSource;
MySqlCommand cmdDb1317466_bk = new MySqlCommand("Select * from db1317466_bk.registration;", conDb1317466_bk);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDb1317466_bk;
DataTable dbdataset1 = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
//DataGridView1.DataSource = bSource;
DataGridView1.DataBind();
sda.Update(dbdataset);
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Can Load data');</script>");
}
}
}
Try this one
GridView1.DataSource=dbdataset;
GridView1.DataBind();
Instead of using
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
DataGridView1.DataBind();
Also, I don't think that you should use:
sda.Update(dbdataset);
Try this
try
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmdDb1317466_bk;
DataTable dt= new DataTable();
da.Fill(dt);
DataGridView1.DataSource = dt;
DataGridView1.DataBind();
}
I've a database in MS Access.
And i'm placing the data in the database to datagridview on form load.
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "/Db.mdb";
OleDbConnection conObj = new OleDbConnection(connectionString);
conObj.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("SELECT * FROM StopMaster", conObj);
da.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
conObj.Close();
on execution, it'll show datagridview with the items in the database,
along with an empty row where we can add new data
and if we click on the existing row's items with data we can update it and even remove it
how to code for that update delete and add and reflect to the database
is there any event or what
also how can i make data grid view columns not resizable.
also say if i have two columns "name" and "pin code" in the datagridview when i click on column header say for now "pin code"it must sort the datagridview rows in order
is there any event and how to for that too
The first thing to mention, is that you will need to Bind your data table to the Datagridview. This is so that any changes you make whilst editing the DataGridView control reflect directly through to the underlying DataTable.
I'll assume that you have already populated the DataTable object.
You start by creating BindingSource object :-
BindingSource bs = new BindingSource();
bs.Datasource = dt;
Now we need to make this Binding Object the datasource for your DataGridView Control :-
dataGridView1.DataSource = bs;
In a method, you can use the following code to commit changes :-
using (OleDbConnection con = new OleDbConnection(connectionString))
{
var adaptor = new OleDbDataAdapter();
adaptor.SelectCommand = new OleDbCommand(""SELECT * FROM [StopMaster]", con);
var cbr = new OleDbCommandBuilder(adaptor);
cbr.GetDeleteCommand();
cbr.GetInsertCommand();
cbr.GetUpdateCommand();
try
{
con.Open();
adaptor.Update(dt);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message, "OledbException Error");
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Exception Error");
}
}
Rather than use the designer I'm trying to populate a DataGridView I've put on my Winform programmatically. When I look in the table under the debugger it has the correct columns and number of rows. The problem is the grid appears as an empty grey box on my form. When I bind the grid to the database via VS 2008 Designer it worked fine. How can I track down the problem?
UPDATE
I pretty much took this from this MSDN Article
UPDATE
Do I have to do anything in the designer other than drop the grid on the Winform?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Windows.Forms;
namespace CC
{
public partial class Form1 : Form
{
private BindingSource bindingSource1 = new BindingSource();
private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
public Form1()
{
InitializeComponent();
dataGridView1 = new DataGridView();
this.Load += new System.EventHandler(Form1_Load);
this.Text = "Cars";
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Cars");
}
private void GetData(string selectCommand)
{
string dbPath = "c:\\temp\\cars.db";
try
{
var connectionString = "Data Source=" + dbPath + ";Version=3";
dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
}
I think you need to specify the DataMember property. And I think you don't require binding source object, directly you can bind DataTable to DataGridView control.
I am attaching a code which helps to bind gridview control with SQL Server database, and it works fine for me.
using(SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter("SELECT * FROM Table1",
"Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
this.dataGridView1.DataSource = dataTable;
}
}
Sorry I don't have SQLite installed :(
basically i dont think u should complicate this! here's an easy way:
string cs = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your db location;"; //connection string
string sql = "SELECT * FROM table_name"; //sql statment to display all data
OleDbConnection conn = new OleDbConnection(cs); //connectiion
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //data adapter object
DataSet ds = new DataSet(); //dataset object to keep data in table
conn.Open(); //open connection
da.Fill(ds, "table_name"); // fill the dataset with table_name through data adapter
conn.Close(); //close connection
dataGridView1.DataSource = ds; //populate the datagridview with dataset
dataGridView1.DataMember = "table_name"; // populate datagridview with table_name
I have has difficulties with sqlite and also binding with linq. Now I have the same issue as above and ended up looping the data table to fill the grid.
I have noticed other minor issues with sqlite when using datatables and also databinding so I guess the problem lies with sqlite.
Here's some code to save time for anyone.
int rowcount = 0;
foreach (DataRow row in dataTable.Rows)
{
dataGrid.Rows.Add();
int column = 0;
foreach (var item in row.ItemArray)
{
dataGrid.Rows[rowcount].Cells[column].Value = item;
column++;
}
rowcount++;
}