在dataGridView列中访问组合框?
我正在调度程序,并在dataGridView中,我们有几个ComboBox列在创建时由3个条目填充,但我希望能够添加更多,因为用户创建它们,但我没有想法你将如何访问组合框数据。任何帮助表示赞赏!在dataGridView列中访问组合框?
// this is initialized in a separate part.
/* System::Windows::Forms::DataGridView^ dataGridView;*/
System::Windows::Forms::DataGridViewComboBoxColumn^ newCol =
(gcnew System::Windows::Forms::DataGridViewComboBoxColumn());
dataGridView->Columns->AddRange(gcnew cli::array<System::Windows::Forms::DataGridViewComboBoxColumn^>(1) {newCol});
// add the choices to the boxes.
newCol->Items->AddRange("User inputted stuff", "More stuff", "Add New...");
解决方案
如果你有机会从用户输入的数据,你知道的DataGridViewComboBoxColumn
列索引,你应该能够做到以下几点哪里需要只是:
DataGridViewComboBoxColumn^ comboboxColumn = dataGridView->Columns[the_combobox_column_index];
if (comboboxColumn != nullptr)
{
comboboxColumn->Items->Add("the new user entry");
}
意见的回应
如何更改该组合框的选定索引( 编辑触发的那个)? [...]我们希望它能够在添加新项目 时将所选索引设置为该新项目)。
几个想到的方法。
-
在上述代码的
if-statement
中添加一行。这将为DataGridViewComboBoxColumn
中的每个DataGridViewComboBoxCell
设置默认显示值。if (comboboxColumn != nullptr) { comboboxColumn->Items->Add("the new user entry"); comboboxColumn->DefaultCellStyle->NullValue = "the new user entry"; }
- 优点:清洁,高效。以前用户选择的值为,保持不变。如果没有其他选择,单元格的
FormattedValue
将默认显示新的用户值。 - 缺点:实际上设置了单元格的选定值,所以
Value
将在未明确用户选择的单元格上返回null
。
- 优点:清洁,高效。以前用户选择的值为,保持不变。如果没有其他选择,单元格的
-
实际上设置某些细胞对用户添加的值的值(根据您的标准)。
if (comboboxColumn != nullptr) { comboboxColumn->Items->Add("the new user entry"); for (int i = 0; i < dataGridView->Rows->Count; i++) { DataGridViewComboBoxCell^ cell = dataGridView->Rows[i]->Cells[the_combobox_column_index]; if (cell != nullptr /* and your conditions are met */) { cell->Value = "the new user entry"; } } }
- 优点:靶细胞的
Value
是实际上设置为新的用户价值。 - 缺点:逻辑决定哪个细胞应该受到影响更为复杂。
- 优点:靶细胞的
首先感谢您的回答。现在,考虑到'comboboxColumn',你怎么能改变该组合框的选定索引(编辑触发的那个)呢? (我知道这不是问题的一部分,但我正在与Ralis一起开展项目,我们希望它能够在添加新项目时将所选索引设置为新项目) – StephenButtolph
@StephenB编辑我的答案解决您的其他问题。希望有所帮助。如果我误解了任何内容,请告诉我。 – OhBeWise
非常感谢您,我认为这正是我们所需要的。当我周一看到他时,我会确保拉利斯接受这个答案。再次感谢! – StephenButtolph
我很困惑。它不是**用户**,它创建条目。这是**您的应用程序**,代表用户。我不知道,你如何实现这个功能,现在请求帮助实现相同的功能。我错过了什么? – IInspectable
列中有下拉组合框,当用户选择“添加新”时,它们会显示一个请求新输入的文本框。然而,当它输入时,我不知道如何将它添加到组合框中以供将来选择。 – Ralis
显示如何在开始的'ComboBoxColumn'中添加项目 – Fabio