質問
私はしばらくこれに苦労してきました。選択コマンドを初期化したと思っていたのに、以下のエラーが発生しましたか?
dataadapter.selectcommand.connection プロパティを初期化する必要があります
これが問題になる可能性があることを読んだので、主キーが設定されていないためにこのエラーが発生しないことはわかっています。私は間違いなく主キーを持っています。
バックグラウンド
この関数は、if ステートメントを使用して呼び出されるクエリを選択します。クエリ内には、エンド ユーザーが 2 つのコンボボックスで選択した内容に基づいて選択されるパラメーター化された変数があります。
SQLSelection();
クエリの例
SQL = "SELECT * FROM dbo.joblist_TEST WHERE username = @username and status in ('New','Hold')";
動作していないビットは、Update_Click
イベント ハンドルです。
コード
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());
}
}
}