简体   繁体   English

你调用的对象是空的。 C#和访问

[英]object reference not set to an instance of an object. c# and access

hello am working on back up access database using C#, i have four groups which is access configuration , database selection, database backup and database restore. 您好,我正在使用C#备份访问数据库,我有四个组,分别是访问配置,数据库选择,数据库备份和数据库还原。 so on data configuration i have data source textbox user id textbox and password textbox on database selection i have database combbox so that i can select one so i wrote this code 所以在数据配置上,我在数据库选择上有数据源文本框用户ID文本框和密码文本框,还有数据库组合框,因此我可以选择一个,因此我编写了此代码

 public partial class Form11 : Form
{
    private OleDbConnection conn;
    private OleDbCommand command;
    private OleDbDataReader reader;
    string ole = "";
    string connectionString = "";


    public Form11()
    {
        InitializeComponent();
    }

    private void BtnConnect_Click(object sender, EventArgs e)
    {
        try
        {
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
                                   @"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";
            conn = new OleDbConnection(connectionString);
            conn.Open();
            ole = "EXEC sp_databases";
            command = new OleDbCommand(ole, conn);
            reader = command.ExecuteReader();
            cmbDatabases.Items.Clear();
            while (reader.Read())
            {
                cmbDatabases.Items.Add(reader[0].ToString());
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
}

the problem is i keep seeing object reference not set to an instance of an object, here i use access database but on SQL i didn't have such problem, please help me out with this thing. 问题是我一直看到对象引用未设置为对象的实例,在这里我使用访问数据库,但是在SQL上我没有这样的问题,请帮我解决这个问题。 thank you. 谢谢。

Conn is an object and is not instantiated yet when you are using conn.ConnectionString property Conn是一个对象,在使用conn.ConnectionString属性时尚未实例化
just flip the order this 2 lines 只需翻转这2行的顺序

  try
        {
            conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
                                   @"Data Source = "+txtDataSource.Text+"; User Id="+txtUserId.Text+"; Password="+txtPassword.Text+"";

In your code, you are using your connection before instantiating your connection object. 在您的代码中,您在实例化连接对象之前正在使用连接。 You need this first: 您首先需要这个:

conn = new OleDbConnection();

The error should have referenced a line in your code that you were getting this problem - often relatively easy to track back from there to see what is null. 该错误应该已经在您的代码中引用了您遇到此问题的一行-通常相对容易从那里追溯以了解什么是null。

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

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