我想你可以創建一個自定義的MyDataGridViewCheckBoxCell並覆蓋它的GetFormattedValue來返回true \ false,取決於存在單元的值在你的集合中;和SetValue來修改集合。請看下面的例子是否適合你的工作。不知道這是否是做到這一點的最好辦法,但它不是哈克這是肯定的:)
private static List<string> ItemsList = new List<string>();
...
// fill in collection list
ItemsList.AddRange(new string[] { "a", "c" });
// create columns
DataGridViewTextBoxColumn column0 = new DataGridViewTextBoxColumn()
{ HeaderText = "column1", DataPropertyName = "Column1"};
DataGridViewCheckBoxColumn column1 = new NewDataGridViewCheckBoxColumn()
{ HeaderText = "column2", DataPropertyName = "Column2"};
dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { column0, column1 });
// create data rows
dataSet1.Tables[0].Rows.Add(new object[] {"a", "a" });
dataSet1.Tables[0].Rows.Add(new object[] { "b", "b" });
dataSet1.Tables[0].Rows.Add(new object[] { "c", "c" });
...
// custom datagridview checkbox cell
public class MyDataGridViewCheckBoxCell : DataGridViewCheckBoxCell
{
public MyDataGridViewCheckBoxCell()
{
FalseValue = false;
TrueValue = true;
}
protected override Object GetFormattedValue(Object value,
int rowIndex,
ref DataGridViewCellStyle cellStyle,
TypeConverter valueTypeConverter,
TypeConverter formattedValueTypeConverter,
DataGridViewDataErrorContexts context)
{
// check if value is string and it's in the list; return true if it is
object result = (value is string) ? Form1.ItemsList.IndexOf((string)value) > -1 : value;
return base.GetFormattedValue(result, rowIndex, ref cellStyle,
valueTypeConverter, formattedValueTypeConverter, context);
}
protected override bool SetValue(int rowIndex, Object value)
{
if (value!=null)
{
// change collection
if (value.Equals(true))
Form1.ItemsList.Add((string)Value);
else
Form1.ItemsList.Remove((string)Value);
// dump list into console
foreach (string item in Form1.ItemsList)
Console.Write("{0}\t", item);
Console.WriteLine();
}
return true;
}
}
// custom datagridview column
public class NewDataGridViewCheckBoxColumn : DataGridViewCheckBoxColumn
{
public NewDataGridViewCheckBoxColumn()
{
CellTemplate = new MyDataGridViewCheckBoxCell();
}
}
希望這會有所幫助,至於