- 填充DataTable,並用它作爲一個比南源的DataGridView
1.1不要在datagridview的變化...
public void DAL_UpdateStudentsTable(DataTable table) //DAL represents 3-tyer architecture (so data access layer)
{
using (SqlConnection sqlConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = @"UPDATE Students SET " +
"StudentID = @id, " +
"FirstName = @first, " +
"LastName = @last, " +
"Birthday = @birthday, " +
"PersonalNo = @personal " +
"WHERE StudentID = @oldId";
cmd.Parameters.Add("@id", SqlDbType.Int, 5, "StudentID");
cmd.Parameters.Add("@first", SqlDbType.VarChar, 50, "FirstName");
cmd.Parameters.Add("@last", SqlDbType.VarChar, 50, "LastName");
cmd.Parameters.Add("@birthday", SqlDbType.DateTime, 1, "Birthday");
cmd.Parameters.Add("@personal", SqlDbType.VarChar, 50, "PersonalNo");
SqlParameter param = cmd.Parameters.Add("@oldId", SqlDbType.Int, 5, "StudentID");
param.SourceVersion = DataRowVersion.Original;
cmd.Connection = sqlConn;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.UpdateCommand = cmd;
da.Update(table);
}
}
}
}
- 當你想更新數據庫只需創建一個更新命令,並像上面所看到的那樣執行它。
謝謝。對於列表這個根本不是IBindingList實現的數據源,是否意味着AllowUserToAddRows或AllowUserToDeleteRows屬性足以確定是否允許添加或刪除行?列表似乎支持添加除了您的結論中的編輯和刪除。謝謝 –
編輯'DataGridView'中'List'的唯一方法是使用'BindingSource'。根據綁定源規則,如果您將'List '設置爲'BindingSource'的數據源,然後將'BindingSource'設置爲'DataGridView'的數據源,那麼您可以*添加*,*編輯*和*刪除*清單'的項目。 –
除了上述支持* Add *的條件之外,別忘了使用公共無參數的構造函數(通常在普通類中有這個)。 –