问题
我已经为此苦苦挣扎了一段时间。虽然我认为我已经初始化了 select 命令,但我有以下错误?
dataadapter.selectcommand.connection 属性需要初始化
我知道由于没有设置主键,我没有收到此错误,因为我已阅读这可能是问题所在。我肯定有一个主键。
背景
此函数选择使用 if 语句调用的查询。在查询中有参数化变量,这些变量是根据最终用户在两个组合框中选择的内容来选择的。
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());
}
}
}