C# database connection and datagridview

17,268

A DataSet can contain multiple DataTables. You could set the DataGridView's data source to a specific table in the DataSet, or just use a DataTable:

DataTable table = new DataTable();
dadapter.Fill(table);
con.Close();
this.dataGridView1.DataSource = table;

On a side note, you can use using to help clean up resources:

string strCon = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Users\User\Desktop\Numeratori.accdb;";
string strSql = "select * from tabela";

using (OdbcConnection con = new OdbcConnection(strCon))
using (OdbcDataAdapter dadapter = new OdbcDataAdapter(strSql, con))
{
    DataTable table = new DataTable();
    dadapter.Fill(table);

    this.dataGridView1.DataSource = table;
}
Share:
17,268

Related videos on Youtube

user670255
Author by

user670255

Updated on June 04, 2022

Comments

  • user670255
    user670255 almost 2 years

    I recently started using databases in C# but I'm not figuring out something! In Visual Studio 2008 I started a new project, added a datagridview to the form, and on form_load I put this code:

    string strCon = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Users\User\Desktop\Numeratori.accdb;";
    string strSql = "select * from tabela";
    OdbcConnection con = new OdbcConnection(strCon);
    con.Open();
    OdbcDataAdapter dadapter = new OdbcDataAdapter();
    dadapter.SelectCommand = new OdbcCommand(strSql, con);
    DataSet dset = new DataSet();
    dadapter.Fill(dset);
    con.Close();
    this.dataGridView1.DataSource = dset;
    

    When I run it the form opens up but in the datagridview there is no data! what should I do?

  • user670255
    user670255 about 13 years
    thnx for the answer :D just tried this but still the same problem the datagridview is empty :\
  • Jeff Ogata
    Jeff Ogata about 13 years
    @user670255, hmm... this should work. Just to check, are you sure there is data in that table? If you put a breakpoint on the line where you set dataGridView1.DataSource = table;, is there data in table?
  • user670255
    user670255 about 13 years
    yes it is! i created the columns in ms access and added some data in rows! i also tried to do it not from form load but with a button click and now i came up with an error: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
  • Jeff Ogata
    Jeff Ogata about 13 years
    @user670255, the only other thing I can think of is that AutoGenerateColumns is false. true is the default value, but you might want to check and make sure. Other then that, I tried code similar to this using Sql Server, and it filled the data grid. I don't have much experience w/ Access, so can't help with your other error. Sorry!