我在 Winform 的 DataGridView 内的 DataGridViewComboBoxColumn 中保留用户的选择时遇到问题。一旦我离开组合框,选择就会消失。
我找到了一些问题的答案,例如将 SelectedIndex 设置为 -1,但它没有用。请指出我正确的方向。
提前致谢。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Create DataTable.
DataColumn classIdColumn = new DataColumn("Class", typeof(string));
_schoolTable = new DataTable("School");
_schoolTable.Columns.AddRange(new[] { classIdColumn });
DataRow row = _schoolTable.NewRow();
row["Class"] = "yr 5";
_schoolTable.Rows.Add(row);
// Bind DataGridView to DataTable, and add ComboBoxColumn.
dataGridView1.DataSource = _schoolTable;
DataGridViewComboBoxColumn listCol = new DataGridViewComboBoxColumn();
listCol.DisplayIndex = 1;
listCol.DataSource = GetChoices();
listCol.DisplayMember = "Category";
listCol.ValueMember = "Number";
listCol.DefaultCellStyle.NullValue = "None";
dataGridView1.Columns.Add(listCol);
}
private DataTable _schoolTable;
private static List<IHuman> GetChoices()
{
return Choices;
}
private static readonly List<IHuman> Choices = new List<IHuman>(){ new Student(), new Teacher() };
private interface IHuman
{
int Number { get; set; }
string Category { get; }
}
private class Student : IHuman
{
public int Number { get; set; }
public string Category { get { return "student"; } }
}
private class Teacher : IHuman
{
public int Number { get; set; }
public string Category { get { return "teacher"; } }
}
}