datagridview doesn't display data - c#

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...

Related

How to edit dynamically generated datatable and datagridview?

So i have a form that looks like this:
Image Link
and I generate the datatable for the dataviewgrid in the load function:
private void loadEmpresas(){
MySqlConnection myConn = new MySqlConnection(gVariables.myConnection);
MySqlCommand command = new MySqlCommand("Select codempresa as 'Codigo', nomempresa as 'Nombre empresa' from contabilidad.empresas", myConn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
the table in mysql looks like this:
SQL Table Image Link
so when it is running it shows this:
Now the problems that i have are that i have no idea how to modify the width of the columns, id like the entire table to cover that gray space and i want that on click it selects the entire row not just a cell. When it clicks the row i want to pupulate the rest of the textboxes but i have a problem with the click event which for testing purposes is this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("clicked");
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
MessageBox.Show(row.Cells[0].Value.ToString() + row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("wat");
}
}
when I click it doesn't even show a messagebox sometimes, I seriously have no idea how to handle the click row event properly :C help please T_T
For updating the column widths try using DataGridViewColumn.width:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
DataGridViewColumn.Width property information.
To select the entire row you need to change the SelectionMode of the DataGrid to FullRowSelect:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
SelectionMode information.

Search in Database, output in DataGridView

I have a Database with 2 Tables. Now i want to search for Values in my Databases.
I use this GUI so the "User" can give Information to the Textbox and the searched Values should shown in my Datagridview
I use this Code:
private void TB_MSGHeadline_TextChanged(object sender, EventArgs e)
{
try
{
if (TB_MSGHeadline.Text.Equals(""))
{
}
else
{
DataView dv = new DataView(table);
dv.RowFilter = string.Format("MessageHeadline LIKE '%{0}%'", TB_MSGHeadline.Text);
dataGridView1.DataSource = dv;
}
}
catch (Exception i)
{
MessageBox.Show("" + i);
}
}
Fill the DataGridview
private void GetData(string selectCommand)
{
//Creating a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, ConnectionString);
//Create a command builder to generate SQL update, insert, and
//delete commands based on selectCommand. These are used to
//update the Database.
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder();
//Populate a new data table and bind it to the BindingSource
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
BindingSource1.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = BindingSource1;
GetData("SELECT * FROM Tabelle1");
}
(Found it in a video but dont work for my problem)
But i get the Error, that the row "MessageHeadline" wasnt found
So i want to know, how can i make a LIKE search for my SQL Database?

DataGridView linked with DataTable not showing data ODBC

I have a datatable filled using an OdbcAdapter. I know for a fact that this table has data in it because if I put a break point I see that it has 5 columns and a count of 852.
I tried putting this table as the data source of a bindingsource then attaching this bindingsource to a DataGridView as well as setting the table as the DataGridView's source directly.
In both cases, the gridview has 0 rows in it and displays nothing. Any help would be much appreciated.
Here is my code:
private void populateTable() {
String query = "SELECT * FROM MASKENCODE";
OdbcCommand command = new OdbcCommand(query, Program.myConnection);
OdbcDataAdapter adapter = new OdbcDataAdapter(query, Program.myConnection);
DataTable table = new DataTable();
adapter.Fill(table);
table.DefaultView.AllowDelete = false;
table.DefaultView.AllowEdit = false;
table.DefaultView.AllowNew = false;
//table.Locale = System.Globalization.CultureInfo.InvariantCulture;
//bindingSource1.DataSource = table;
//dataGridView1.DataSource = bindingSource1;
dataGridView1.DataSource = table.DefaultView;
if (table.Rows.Count > 0) {
Console.WriteLine("TABLE EXISTS");
}
if (dataGridView1.RowCount > 0) {
Console.WriteLine("GRID EXISTS");
}
}
I always get the "TABLE EXISTS" print but not the "GRID EXISTS" one
Check whether the AutoGenerateColumns is set to true mainly in designer file. If not add the below line of code to automatically generate columns.
dataGridView1.AutoGenerateColumns = true;

C#: Can't populate DataGridView programmatically

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

Datagrid Binding Question

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Categories