简体   繁体   中英

Select Command initialized Error

Question

I've been struggling with this for a while now. I have the error below although I thought I had initialized the select command?

The dataadapter.selectcommand.connection property needs to be initialized

I know I am not getting this error due to having no primary key set, as I have read this can be the problem. I definitely have a primary key.

Background

This function selects what query is called using an if statement. within the queries there are to parametrized variables that are selected based on what the end user selects in two comboboxes.

SQLSelection();

Example Query

   SQL = "SELECT * FROM dbo.joblist_TEST WHERE username = @username and status in ('New','Hold')";

The bit that isn't working is the Update_Click event handle.

Code

 public partial class Form1 : Form
    {
        int weeks = 0;
        SqlCommand command = new SqlCommand();
        SqlDataAdapter adb = new SqlDataAdapter();
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommandBuilder builder = new SqlCommandBuilder();
        SqlCommand selectCommand = new SqlCommand();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection();

        String ConnString = "Data Source=sqlexpress; Initial Catalog=MobileData; User ID=mobile; Password=pw";
}


public DataTable getDataTable()
            {

            //Decide what query
            String SQL = SQLSelection();

            // SqlDbConnection con = new OleDbConnection(ConnString);
            SqlConnection con = new SqlConnection(ConnString);

            //open connection to database
            con.Open();

            //create adapter that sits inbetween dataset and datbase
            SqlDataAdapter adapter = new SqlDataAdapter();


            adapter.SelectCommand = new SqlCommand(SQL, con);
            adapter.UpdateCommand = new SqlCommand(SQL, con);

            adapter.SelectCommand.Parameters.Add("@username", SqlDbType.VarChar).Value = auditorCmb.Text;
            adapter.SelectCommand.Parameters.Add("@status", SqlDbType.VarChar).Value = statusCmb.Text;

            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);


            adapter.Fill(ds, "jobList_Test");
            dt = ds.Tables["jobList_Test"];


            dataGridView1.DataSource = ds.Tables["jobList_Test"];

            int rowCount = rowCount = dt.Rows.Count;
            label10.Text = rowCount.ToString("n0");


            return dt;
        }

        public void Update_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("Are you sure you want to save changes?", "Save Changes", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {

                try
                {


                    adapter.SelectCommand = command; // cmd1 is your SELECT command

                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

                    builder.GetUpdateCommand(); // Force the building of commands
                    adapter.Update(ds, "jobList_Test");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());

                }
            }




        }

The problem is that you didn't set what is the select command you just set adapter.SelectCommand = command; // cmd1 is your SELECT command and i thought that you didn't defined what command is just new sqlCommand... please more info about what are you trying to do thus i can help more.

Your this code adapter.SelectCommand = command; is using an SqlCommand that is initialize with SqlCommand only without a connection specified. I think you also over doing things. Mentioning what you want to achieve may help in getting better answers.

You need to simplify your sample code quite a bit. I don't see where getDataTable() is even being called.

Either way, you are going down a path that is well known for failure. The SqlConnection and SqlCommand objects should never be instantiated as global variables. Instead they should be created and disposed within the calling code block.

Why? Because they implement IDisposable and deal with unmanaged resources. This means that you will leak memory and database connections if / when your program has a problem.

Note that creating and disposing of even thousands of SqlConnection or SqlCommand objects a second will NOT result in a performance problem.

Ultimately, it looks like you are seriously over complicating things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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