C#: Can't populate DataGridView programmatically - c#

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

Related

DataGridView not showing my columns

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

combobox /dropdownlist in grid view c#.net

I am a newbie to c#.net winforms application. I have a data grid wch displays some data and out of which one of the column shud be made a dropdownlist or combobox. how do I use that in my code. please help.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Rows[e.RowIndex].Cells[3].OwningColumn;
sql = "select NAME FROM Suppliers";
BindingSource bsource = new BindingSource();
bsource.DataSource = obj.SqlDataTable(sql);
dataGridView1.DataSource = bsource;
combo.HeaderText = "Select Supplier";
}
I want to populate the 3rd column of the data grid with supplier name from the corresponding suppliers table.The data grid view is already populated with data from a join query and one of the field is Supplier(wch I mwant to convert to a dropdown or combo box). let me know if you need any further info for clarifications.
I Modified my code as follows:
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Suppliers";
//execute sql data adapter to get supplier values
DataTable dt = obj.SqlDataTable("select NAME from CUSTOMERS");
foreach (DataRow supplier in dt.DataSet.Tables[0].Rows)
{
combo.Items.Add(supplier[0]);
}
dataGridView1.Columns.Add(combo);
now am getting a null reference exception at " dt.DataSet.Tables[0].Rows"
. plz help. I am not sure if am missing something.
Try this code
string strcon = #"Data Source=kp;Initial Catalog=Name;Integrated Security=True;Pooling=False";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataGridViewComboBoxColumn dgvCmb;
public Form2()
{
InitializeComponent();
grdcmd();
}
public void grdcmd()
{
con = new SqlConnection(strcon);
con.Open();
string qry = "Select * from Dbname";
da = new SqlDataAdapter(qry, strcon);
dt = new DataTable();
da.Fill(dt);
dgvCmb = new DataGridViewComboBoxColumn();
foreach (DataRow row in dt.Rows)
{
dgvCmb.Items.Add(row["Fname"].ToString());
}
dataGridView1.Columns.Add(dgvCmb);
}

c# DataGridView & oledb

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

datagridview doesn't display data

i want to show the data from the database onto my datagridview control i have used the following piece of code but it is not showing any data when the form loads it just shows and empty datagridview i don't get any errors what am I doing wrong
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
FillData();
}
public void FillData()
{
using (SqlConnection myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=10"))
{
myConnection.Open();
using (SqlDataAdapter sqlDa = new SqlDataAdapter("select * from スコープ", myConnection))
{
DataTable dt = new DataTable();
sqlDa.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
I suspect there is no matching column of datatable with datagridview column....Check the column of datagridview with datatable column....
For test, make dataGridView1.AutoGenerateColumns to true and check whether the datagridview fill the data or not...
dataGridView1.AutoGenerateColumns= true;
You can create the datagridview column by following way:
Go to properties of datagridview and then go to Columns Section where you can add new column in datagridview according to your datatable....Match DataPropertyName with your datatable column and keep AutoGenerateColumns to false and then it'll works fine...

c# datagridview and mysql

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;

Categories