我有一个绑定源,用作数据网格的数据源。绑定绑定源后,我试图交换绑定源的两行。
object currentRow = dashBoardBindingSource[index];
object aboveRow = dashBoardBindingSource[index - 1];
dashBoardBindingSource[index] = aboveRow;
dashBoardBindingSource[index - 1] = currentRow;
上面的代码给了我一个例外如下
Cannot set an object into this list.
我使用以下代码将数据绑定到绑定源
OnlineOutageReport[] outageReports;
dashBoardBindingSource = new BindingSource();
dashBoardBindingSource.DataSource = ToDataTable<OnlineOutageReport>(outageReports);
private static DataTable ToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
任何人都有自己的想法。 感谢
答案 0 :(得分:1)
以下是将bindingSource从DataGridView的一行移动到另一行的方法。
int index = this.KeyDataGridView.SelectedRows[0].Index;
this.KeyDataGridView.ClearSelection();
if (index == this.KeyDataGridView.Rows.Count - 1)
{
return;//can go down
}
var tempKey = this.keysBindingSource[index];
this.keysBindingSource.RemoveAt(index);
this.keysBindingSource.Insert(index + 1, tempKey);
它可能只需要您使用dataSource.Insert(index)而不是