C#数据库连接和datagridview

时间:2011-03-21 22:31:29

标签: c# database datagridview odbc

我最近开始在C#中使用数据库,但我不知道什么! 在Visual Studio 2008中,我启动了一个新项目,向表单添加了一个datagridview,并在form_load上放了这段代码:

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;

当我运行它时,表单会打开,但在datagridview中没有数据! 我该怎么办?

3 个答案:

答案 0 :(得分:5)

DataSet可以包含多个DataTable。您可以将DataGridView的数据源设置为DataSet中的特定表,或者只使用DataTable:

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

另外,您可以使用using来帮助清理资源:

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

答案 1 :(得分:0)

        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;

答案 2 :(得分:0)

如果有帮助,请将这些行添加到您的编码行的最后:

this.dataGridView1.DataMember = "tabela";

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

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