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());
}
}
}