【问题标题】:c# set which item is selected in datagridview combobox cellc#设置在datagridview组合框单元格中选择了哪个项目
【发布时间】:2021-07-15 13:31:41
【问题描述】:

我有两个表格,其中一个我用一些行填写DataGridView,每行有两个组合框。

我能够从这些单元格中获取值和格式化值,但是当我尝试将所有这些数据复制到下一个不同形式的 DataGridView 中时,我无法告诉他来自 @ 的哪个项目987654323@ 应标记为选中。

当我环顾四周时,我发现了这些代码行(不幸的是,它们来自 6 多年前)

dataGridView.Rows[index].Cells[3].Value = ImageFormat.Items[1];

(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = ImageFormat.Items[0];

DataGridViewComboBoxCell comboboxFormat = (DataGridViewComboBoxCell)(dataGridView.Rows[index].Cells[3]);

comboboxFormat.Value = ImageFormat.Items[0];

(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = (dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Items[0];

不幸的是,这些都不起作用,而且大多数(如果不是全部)抛出“DataGridViewComboBoxCell 值无效”异常

也许值得一提的是,可能的项目是从数据库中绑定的,如下所示:

string stm = "SELECT * FROM colours";
            using var cmd = new SQLiteCommand(stm, MainWin.con);
            SQLiteDataAdapter rdr = new SQLiteDataAdapter(cmd);
            DataTable dataTableColour = new DataTable();
            rdr.Fill(dataTableColour);

            stm = "SELECT * FROM formats";
            using var cmdd = new SQLiteCommand(stm, MainWin.con);
            SQLiteDataAdapter reader = new SQLiteDataAdapter(cmdd);
            DataTable dataTableFormat = new DataTable();
            reader.Fill(dataTableFormat);

            ImageFormat.ValueMember = "id";
            ImageFormat.DisplayMember = "name";
            ImageFormat.DataSource = dataTableFormat;

            ColourImage.ValueMember = "id";
            ColourImage.DisplayMember = "name";
            ColourImage.DataSource = dataTableColour;

【问题讨论】:

  • 如果您的 DataGridViewComboBoxColumns 已正确初始化(我假设 ImageFormatColourImage 是 DataGridViewComboBoxCells),您无需做任何事情:每个 ComboBoxCell 将值设置为 DataGridView 的基础数据源。因此,您只需将 DataSource 传递给另一个 Control(最终将 Filter 设置为 DefaultView 或链接的 BindingSource)。或选择的 DataRow 引用。
  • ImageFormat 和 ColourImage 是 DataGridViewComboBoxColumns (或者我猜的标题)。当我试图查看 DGV 的数据源中的内容时,它为空。第二个 DGV 的 ComboBox 列设置方式相同(来自数据库),这可能是多余的或直接错误的。当您获得 ComboBoxCell 的值时,它会为您提供索引,因此我试图将此索引设置为第二个 DGV

标签: c# winforms datagridview datagridviewcomboboxcell


【解决方案1】:

您的 datagridview 应该绑定到某个数据表(比如说 ImageFiles)。将 ColourImage/ImageFormat 组合的 .DataPropertyName 属性设置为组合应编辑的 [ImageFiles] 数据表中的列的名称。不要尝试直接与 DGVCombo 交互;只需与网格绑定的数据表交互

【讨论】:

  • 整个 dgv 没有绑定,只有两个组合框列,但是数据表在我从数据库中提取数据的函数之外不存在,对吧?或者有没有办法在其他地方访问它?另外我基本上需要将每个单元格的值复制到其他 dgv 中,并且 .DataPropertyName 仅用于标题?
  • 我现在做了,我发现我不能在我的项目中使用数据源,因为它在 .NET Core 而不是框架中,并且还不支持
  • 这似乎不是真的:i.stack.imgur.com/S9fPL.png
  • 但是您已经手动创建了它,在您的另一篇文章中,您正在谈论设计方式,如果我打开数据源(正如我将按照您的演练进行的那样),它会显示“不支持此窗口用于选定的项目。启用数据绑定的步骤,请访问:aka.ms/WinForms/DataBinding"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多