33

I'm trying to present query results, but I keep getting a blank data grid. It's like the data itself is not visible

Here is my code:

 private void Employee_Report_Load(object sender, EventArgs e)
 {
     string select = "SELECT * FROM tblEmployee";
     Connection c = new Connection();
     SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
     SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

     DataTable table = new DataTable();
     table.Locale = System.Globalization.CultureInfo.InvariantCulture;
     dataAdapter.Fill(table);
     bindingSource1.DataSource = table;

     dataGridView1.ReadOnly = true;        
     dataGridView1.DataSource = bindingSource1;
}

What's wrong with this code?

user2023203
  • 546
  • 1
  • 12
  • 19

12 Answers12

47

Here's your code fixed up. Next forget bindingsource

 var select = "SELECT * FROM tblEmployee";
 var c = new SqlConnection(yourConnectionString); // Your Connection String here
 var dataAdapter = new SqlDataAdapter(select, c); 

 var commandBuilder = new SqlCommandBuilder(dataAdapter);
 var ds = new DataSet();
 dataAdapter.Fill(ds);
 dataGridView1.ReadOnly = true; 
 dataGridView1.DataSource = ds.Tables[0];
DamienG
  • 6,575
  • 27
  • 43
Don Thomas Boyle
  • 3,055
  • 3
  • 32
  • 54
11
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
sayed hashim
  • 111
  • 1
  • 2
4

You don't need bindingSource1

Just set dataGridView1.DataSource = table;

banging
  • 2,540
  • 1
  • 22
  • 26
2

Try binding your DataGridView to the DefaultView of the DataTable:

dataGridView1.DataSource = table.DefaultView;
Khan
  • 17,904
  • 5
  • 47
  • 59
1

This is suppose to be the safest and error pron query :

    public void Load_Data()
        {
            using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
            {
                var bindingSource = new BindingSource();
                string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
                using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
                {
                    try
                    {
                       SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                        DataTable table = new DataTable();
                        dataAdapter.Fill(table);
                        bindingSource.DataSource = table;
                        recent_slides_grd_view.ReadOnly = true;
                        recent_slides_grd_view.DataSource = bindingSource;
                    }
                    catch (SqlException ex)
                    {
                       MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
                    }
                    finally
                    {
                        connection.Close();
                    }
                }

            }
        }
Develop4Life
  • 7,581
  • 8
  • 58
  • 76
0

You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.

0

You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.

private void Employee_Report_Load(object sender, EventArgs e)
{
        var table = new DataTable();

        var connection = "ConnectionString";

        using (var con = new SqlConnection { ConnectionString = connection })
        {
            using (var command = new SqlCommand { Connection = con })
            {

                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }

                con.Open();

                try
                {
                    command.CommandText = @"SELECT * FROM tblEmployee";
                    table.Load(command.ExecuteReader());

                    bindingSource1.DataSource = table;

                    dataGridView1.ReadOnly = true;
                    dataGridView1.DataSource = bindingSource1;

                }
                catch(SqlException ex)
                {
                    MessageBox.Show(ex.Message + " sql query error.");
                }

            }

        }

 }
Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40
0

you have to add the property Tables to the DataGridView Data Source

 dataGridView1.DataSource = table.Tables[0];
  • There is already the accepted answer, that provides as well way more information than you do. This here is quite redundant. – L. Guthardt Nov 30 '17 at 12:25
0

if you are using mysql this code you can use.

string con = "SERVER=localhost; user id=root; password=; database=databasename";
    private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Miguel
  • 26
  • 4
0

Years late but here's the simplest for others in case.

String connectionString = @"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";

SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);

DataTable data = new DataTable();
sda.Fill(data);

DataGridView1.DataSource = data;

Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.

Red Magda
  • 398
  • 4
  • 17
0

I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:

1/

using System.Data; AND using MySql.Data.MySqlClient;

2/

MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
        MySqlCommand cmd = new MySqlCommand();

3/

public void SetCommand(string SQL)
{
    cmd.Connection = con;
    cmd.CommandText = SQL;

}
private void FillGrid()
{
    SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
    DataTable tbl = new DataTable();
    tbl.Load(cmd.ExecuteReader());
    dataGridView1.DataSource = tbl;
}
Yun
  • 3,056
  • 6
  • 9
  • 28
0

for oracle:

        var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
        OracleConnection connection = new OracleConnection();
        connection.ConnectionString = connString;
        connection.Open();          
        var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
        var dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
ozanmut
  • 2,898
  • 26
  • 22