gpt4 book ai didi

C# Datagridview ComboBox 选择值棒

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:32 26 4
gpt4 key购买 nike

我希望能够在数据 GridView 的组合框中显示选定的条目。我已经填充了组合框,并且我已经知道如何从数据库中获取选定的值。我想要完成的是在加载表单的任何时候,组合框中的任何预选值都会自动预选,以向用户显示他们最后选择的内容。我有一个存储选择的数据库,并且可以轻松访问它们。同样,我如何才能使选择坚持用户选择的内容,以便每次打开表单时都会记住他们,除非有人更改他们的选择并保存。我没有像往常一样在 datagridview 组合框中看到 value.selected。有没有人让这个工作?

这是一个例子:

我在名为 test 的数据网格中嵌入了一个组合框作为列名

有4个字段可供选择:

  1. test1
  2. test2
  3. test3
  4. test4

假设这次我选择 test3 作为我的选择。我关闭表单并将选择保存到数据库中。现在我知道如何从数据库中检索该值,但是我如何让测试 3 在表单作为显示成员加载时显示,并且如果我愿意,仍然能够选择另一个?

最佳答案

按如下方式处理 Cell Validating 事件......

void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (cell is DataGridViewComboBoxCell)
{
DataGridViewComboBoxCell cell = DataGridViewComboBoxCell)dataGridView1.CurrentCell;
cell.Items.Clear();
cell.Items.Add(e.FormattedValue);
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
cell.Value = e.FormattedValue;
}
}

基本上,您必须将所选值添加到单元格的项目集合中,然后将值设置为添加的值。如果该值不在项目集合中,您将在单元格上收到 DataError 事件。

单元格项目集合与 ComboBox 项目集合不同。

这就是如何根据选择处理设置单元格的值。

如果您处理了 datagridview 的 EditingControlShowing 事件,您可以在单击时访问组合框控件,并在为用户绘制之前将所选项目设置为单元格的当前值。

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell is DataGridViewComboBoxCell
&& e.Control is DataGridViewComboBoxEditingControl)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1.CurrentCell;
ComboBox ctrl = (ComboBox)e.Control;
// Get Currently selected value...
string curValue = String.Empty;
if (cell.Value != null)
curValue = cell.Value.ToString();

//bind data
ctrl.DataSource = dataBaseData;
//set selected value
ctrl.SelectedItem = curValue;
}

}

关于C# Datagridview ComboBox 选择值棒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com