如果我将 DataGridView(dgv) 绑定到适配器,则 dgv 会自动填充表的内容。但是,现在显示为文本的列之一,我想将其更改为 ComboBox。
此代码准备一个数据适配器:
MySqlDataAdapter awardsAdapter, spendingsAdapter;
DataSet cachedData = new DataSet();
MySqlDataAdapter PrepareSpendingsAdapter() {
try {
MySqlDataAdapter adapter;
adapter = new MySqlDataAdapter("select * from spendings", connection);
adapter.TableMappings.Add("Table", "spendings");
adapter.UpdateCommand = new MySqlCommand(
"UPDATE spendings SET category=@category, points=@points WHERE id=@id;",
connection);
adapter.UpdateCommand.Parameters.Add("@id", MySqlDbType.Int32, 10, "ID");
adapter.UpdateCommand.Parameters.Add("@category", MySqlDbType.Int32, 10, "Category");
adapter.UpdateCommand.Parameters.Add("@points", MySqlDbType.Int32, 10, "Points");
adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
adapter.InsertCommand = new MySqlCommand(
"INSERT INTO spendings VALUES (@id,@category,@points);",
connection);
adapter.InsertCommand.Parameters.Add("@id", MySqlDbType.Int32, 10, "ID");
adapter.InsertCommand.Parameters.Add("@category", MySqlDbType.Int32, 10, "Category");
adapter.InsertCommand.Parameters.Add("@points", MySqlDbType.Int32, 10, "Points");
adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
adapter.DeleteCommand = new MySqlCommand(
"DELETE FROM spendings WHERE id=@id;", connection);
adapter.DeleteCommand.Parameters.Add("@id", MySqlDbType.Int32, 10, "ID");
adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
return adapter;
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
return null;
}
此代码添加了一个额外的列,其中包含我需要的信息
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
MySqlDataAdapter adapterSpendCategory = new MySqlDataAdapter("select category,details from spendcategory", connection);
adapterSpendCategory.TableMappings.Add("Table", "spendcategory");
adapterSpendCategory.Fill(cachedData);
cmb.DataSource = cachedData.Tables["spendcategory"];
cmb.DisplayMember = "details";
cmb.ValueMember = "category";
//Put the missing piece of the puzzle here
此代码填充 DataGridView:
spendingsAdapter = PrepareSpendingsAdapter();
spendingsAdapter.Fill(cachedData);
dgvPointsSpent.DataSource = cachedData.Tables["spendings"];
而不是添加这个额外的列,我希望类别列改变并且看起来像额外的列