如何在数据网格视图中查看 MS Access 中的数据?

问题描述 投票:0回答:3

我是 C-Sharp 的新手,我正在尝试从 C-Sharp 访问我的数据库,我编写了以下代码,但我不知道接下来要写什么来查看数据。我在网上搜索过这个,但没有得到太多。请用简单的代码告诉我这一点。

string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";

OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);

OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
c# database-connection ms-access-2007
3个回答
9
投票

参考以下代码:

string strProvider = "@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;

希望它有帮助。


0
投票

试试这个

        try
        {

        Dataset myDataSet=new Dataset();

        string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
        OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );

        connection .Open();
        myDataAdapter.Fill(myDataSet,"TableName");

        }
        catch (Exception ex)
        {
              Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
              return;
        }
        finally
        {
              connection .Close();
        }

请记住,为了良好的编码习惯,应始终在 Try Block 中打开连接 并于 Finally Block

关闭

0
投票
public void refreshdata()  
{  


    OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\nilu\Desktop\Database1.accdb");  
    OleDbCommand cmd = new OleDbCommand("select * from tbl_data",con);  
    OleDbDataAdapter olda = new OleDbDataAdapter(cmd);  
    DataTable dt = new DataTable();  
    olda.Fill(dt);  
      
  
    GridView1.DataSource = dt;  
    GridView1.DataBind();  


}  
© www.soinside.com 2019 - 2024. All rights reserved.