none
Populating table with Update Command? RRS feed

  • Question

  • Here is my code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    
    namespace adoPractice
    {
        public partial class Form1 : Form
        {
            SqlCommandBuilder cmb = new SqlCommandBuilder();
            SqlConnection cs = new SqlConnection();
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
    
            public Form1()
            {
                InitializeComponent();
                SqlConnection cs = new SqlConnection("Data Source=MACHINE;Initial Catalog=ADO_PRACTICE;Integrated Security=True");
                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblContacts", cs);
                DataSet ds = new DataSet();
                SqlCommandBuilder cmb = new SqlCommandBuilder(da);
                da.Fill(ds, "tblContacts");
                dg.DataSource = ds.Tables["tblContacts"];
                                                          
                                                          
            }
    
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                da.UpdateCommand = cmb.GetUpdateCommand();
                da.Update(ds.Tables ["tblContacts"]);
            }
        }
    }
    
    When I compile the program it runs but when I try to populate the table tblContacts the program stops responding and throws this exception:
    System.InvalidOperationException was unhandled
      Message="The DataAdapter.SelectCommand property needs to be initialized."

    Why is that and how can I make it work?
    Thursday, June 25, 2009 7:31 PM

Answers

  • You are declaring SqlCommandBuilder at the class level and then again inside your Form1 constructor. when you run the click handler it is looking at the one at the class level that has not been initialized.

    Do not declare the one inside the Form1 constructor with new just use cmb it is already declared at the class level.
    • Marked as answer by HTopalov Saturday, July 25, 2009 8:58 AM
    Thursday, June 25, 2009 7:42 PM