如何从数据库中读取数据并将其显示在TextBox中?

时间:2012-03-31 20:22:56

标签: c# ms-access

我尝试从MS-Access表中获取一个数据列,并将其显示在像这样的TextBox中

public partial class Form1 : Form
{
    public OleDbConnection database;

    public Form1()
    {
        InitializeComponent();
    }

    private OleDbConnection Database_Connection;

    private void Open_Database_button_Click(object sender, EventArgs e)
    {
        Database_Connection = new OleDbConnection(
            "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="test.mdb");
        OleDbCommand Command = new OleDbCommand(
            " SELECT top 1 * from test", Database_Connection);
        Database_Connection.Open();
        OleDbDataReader DB_Reader = Command.ExecuteReader();

        // How can I display the column in TextBox?
    } 

    ...
}

1 个答案:

答案 0 :(得分:3)

尝试以这种方式更改Open_Database_button_Click:

private void Open_Database_button_Click(object sender, EventArgs e) 
{ 
    using(OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb" )) 
    using(OleDbCommand Command = new OleDbCommand(" SELECT top 1 * from test", con)) 
    {
       con.Open(); 
       OleDbDataReader DB_Reader = Command.ExecuteReader(); 
       if(DB_Reader.HasRows)
       {
          DB_Reader.Read();
          textbox1.Text = DB_Reader.GetString("your_column_name");
       }
    }  
}

我已更改/添加的内容:

  • 删除了全局var DataBase_Connection
  • using添加到Disposable对象,因此它们会自动生成 不再需要时关闭
  • 添加了对DB_Reader.HasRows的检查以从中排除空结果 查询
  • 添加了文本框的text属性设置,其值为 你的一个专栏