简体   繁体   English

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

[英]How do I read data from a database and display it in a TextBox?

I try to get one data column from a MS-Access table and display it in a TextBox like this 我尝试从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?
    } 

    ...
}

Try to change your Open_Database_button_Click in this way: 尝试通过以下方式更改您的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");
       }
    }  
}

What I have changed/added: 我更改/添加的内容:

  • Removed the global var DataBase_Connection 删除了全局var DataBase_Connection
  • Added using to the Disposable objects, so they will automatically closed when no more needed 向一次性对象添加了using ,因此它们将在不需要时自动关闭
  • Added check on DB_Reader.HasRows to exclude empty results from the query 添加了对DB_Reader.HasRows的检查,以从查询中排除空结果
  • Added setting of the text property of the textbox with the value of one of your columns 使用您的其中一列的值添加了文本框的text属性的设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM