开发者

C# database connection and datagridview

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);
Data开发者_StackOverflow社区Set 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?


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


        SqlConnection sql_connect = new SqlConnection();
        SqlCommand sql_command = new SqlCommand();
        string connetionString = @"server=ALI-LAP\SQLEXPRESSR2;Trusted_Connection=yes;database=XXX;";

         SqlDataAdapter sql_ada = new SqlDataAdapter();
         DataTable dt = new DataTable();

                sql_connect.ConnectionString = connetionString;
                sql_command.Connection = sql_connect;
                sql_command.CommandText = "SELECT * FROM XXX";

                sql_ada.SelectCommand = sql_command;
                sql_ada.Fill(dt);

                dataGridView.DataSource = dt;


May this help, add these lines to the last of your coding line:

this.dataGridView1.DataMember = "tabela";

and better put this line before `con.Close();

this.dataGridView1.DataSource = dset;
this.dataGridView1.DataMember = "tabela";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜