DataGridView DataGridViewComboBoxCell value does not change
本文关键字:not change does value DataGridViewComboBoxCell DataGridView | 更新日期: 2023-09-27 17:49:49
我有这个数据视图,一些行的单元格可能是一个组合框。我可以绑定组合框并正确初始化,但是当我从该组合框中选择一个项目时,控件的Value属性保持不变,但格式化的值更改为新选择的项目。
下面是我如何将组合框加载到我的网格视图:
private void ADDComboBoxItemToView(string itemName, Languages.LanguagesEnum language = Languages.LanguagesEnum.English)
{
DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();
c.DataSource = LanguagesManager.LanguageNames.GetLanguages();
c.ValueType = typeof(Languages.LanguagesEnum);
c.Value = language;
c.ValueMember = "LangID";
c.DisplayMember = "LangName";
c.FlatStyle = FlatStyle.System;
var id = dgItems.Rows.Add(new object[] { filePath });
dgItems.Rows[id].Cells[1] = c;
}
这是我的数据源类
public class LanguageNames
{
public Languages.LanguagesEnum LangID { get; set; }
public int LangNum
{
get { return (int) LangID; }
}
public string LangName
{
get { return GetLanguageName(LangID); }
}
private string GetLanguageName(Languages.LanguagesEnum id)
{
switch (id)
{
case Languages.LanguagesEnum.English:
return "English";
case Languages.LanguagesEnum.Finnish:
return "Finnish";
case Languages.LanguagesEnum.French:
return "French";
default:
return string.Empty;
}
}
public static List<LanguageNames> GetLanguages()
{
return _languages;
}
private static readonly List<LanguageNames> _languages = new List<LanguageNames>
{
new LanguageNames{LangID = Languages.LanguagesEnum.English},
new LanguageNames{LangID = Languages.LanguagesEnum.Finnish},
new LanguageNames{LangID = Languages.LanguagesEnum.French}
};
}
我是这样处理选择改变事件的:
private void dgItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dgItems.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
}
}
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var currentcell = dgItems.CurrentCellAddress;
DataGridViewTextBoxCell celItem = (DataGridViewTextBoxCell)dgItems.Rows[currentcell.Y].Cells[0];
DataGridViewComboBoxCell celLang = (DataGridViewComboBoxCell)dgItems.Rows[currentcell.Y].Cells[1];
var item = celItem.Value.ToString();
var language = (Languages.LanguagesEnum) celLang.Value;
_IsSaveRequired = true;
}
这里的问题是celLang.Value
总是返回English
,无论我在组合框中的语言之间改变多少次。然而,如果我调用celLang.FormattedValue
,我得到正确的语言字符串。
我确实需要语言值作为Enum,不能从FormattedValue中获益。
如果我不初始化组合框,删除c.Value = language;
行,我得到一个"对象引用"异常在var language = (Languages.LanguagesEnum) celLang.Value;
和celLang.Value
为空;
有人能帮忙吗?
编辑:这是语言的枚举数:
public enum LanguagesEnum
{
English,
Finnish,
French
}
如果有人有同样的问题,请尝试将DataGridViewComboBoxColumn.DisplayStyle
更改为ComboBox
。默认为DropDownButton
。我也有同样的问题,在这个改变之后,一切都正常工作。