据我所知,我需要更新数据表,而数据表又会更新数据库。所以我尝试在按钮点击事件中使用如下所示的更新命令。
adb.Update(dt);
然而这似乎不起作用,所以我显然遗漏了一些东西,但我不确定是什么?。
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = @username and status = @status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("@username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("@status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
答案 0 :(得分:1)
据我所知,SqlDataAdapter本身不会生成插入,更新或删除命令。
您必须手动设置它们 - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx。
或使用SqlCommandBuilder生成它们:
public static DataSet SelectSqlRows(string connectionString, string queryString, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(queryString, connection); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); connection.Open(); DataSet dataSet = new DataSet(); adapter.Fill(dataSet, tableName); //code to modify data in DataSet here builder.GetUpdateCommand(); //Without the SqlCommandBuilder this line would fail adapter.Update(dataSet, tableName); return dataSet; } }