0

如果我将 DataGridView(dgv) 绑定到适配器,则 d​​gv 会自动填充表的内容。但是,现在显示为文本的列之一,我想将其更改为 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"];

而不是添加这个额外的列,我希望类别列改变并且看起来像额外的列

在此处输入图像描述

4

2 回答 2

1

如果您使用设计器添加数据网格视图并选择它,您会看到一些属性的小箭头。您通常使用它来将 datagridview 绑定到绑定源。您还可以使用箭头“编辑列”。对于每个coiumn,您可以选择是否必须显示它,以何种顺序以及必须如何显示数据(作为文本?作为组合框?作为数字?)。

因此,如果您已经设法添加了一个适合您需要的组合框列,您所要做的就是转到“编辑列”,选择您不想看到的列,然后将它们从列中的列表中删除datagridview,或使用该列的属性使其不可见。

通常您不会添加额外的列,而是更改属性以显示组合框而不是文本。

于 2013-04-15T11:55:04.880 回答
0

似乎答案是添加行colCategory.DataPropertyName = "Category"。在调用之前添加这一行就spendingsAdapter.Fill(..)可以了,因为它识别出该列已经存在并且没有创建一个新列。

于 2013-04-25T08:18:53.753 回答