【发布时间】:2012-06-25 12:12:21
【问题描述】:
DataGridView 和 PropertyGrid 之间的数据绑定有点问题。
这是我绑定的对象的代码和DataGridView:
public class Effort
{
public BindingList<EffortCalculationRelation> CalculationRelations { get; set; }
public int ID { get; set; }
// more properties
public Effort()
{
CalculationRelations = new BindingList<EffortCalculationRelation>();
CalculationRelations.Clear();
for (int i=0;i<10;i++)
{
CalculationRelations.Add( new EffortCalculationRelation() { ID = i, Name = "Round:" + i.ToString(), calculation = "Some calc" });
}
}
public Effort(int id) : this()
{
this.ID = id;
// Load all other properties
}
public class EffortCalculationRelation
{
public int ID { get; set; }
public string Name { get; set; }
public string calculation { get; set; }
public int Save()
{
// save or insert and return id or 0 on fail
if (this.ID > 0)
{
return this.Update();
}
else
{
return this.Insert();
}
}
public string Delete()
{
// delete and return "" or errormsg on fail
return "";
}
private int Insert()
{
// insert and return id or 0 on fail
return ID;
}
private int Update()
{
// return affected rows or 0 on fail
return 1;
}
public string Representation
{
get { return String.Format("{0}: {1}", ID, Name); }
}
}
}
datagridview 连接真的很简单,只有一点点样式:
public test()
{
effort = new Effort(1209);
dgv.DataSource = effort.CalculationRelations;
dgv.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
dgv.AllowUserToAddRows = true;
//this.dgv.AllowUserToDeleteRows = false;
dgv.AllowUserToResizeRows = false;
dgv.ReadOnly = true;
dgv.SelectionChanged += (sender, args) =>
{
var selectedObjects =
(from System.Windows.Forms.DataGridViewRow r in dgv.SelectedRows
where r.DataBoundItem != null && r.DataBoundItem.GetType() == typeof(EffortCalculationRelation)
select r.DataBoundItem).ToArray();
// pg is a propertygrid
this.pg.SelectedObjects = selectedObjects;
};
}
所以我的问题是,当我在 datagridview 中选择新行时,propertygrid 中没有显示任何属性。
当我在加载时选择列表中包含对象的行时,我可以编辑属性。
那你能帮忙吗?
【问题讨论】:
-
您提供的代码不能按原样工作。我将使用我相信您跳过的代码对其进行编辑,但请检查我所做的是否正确,并通过进一步的代码准确给出您所拥有的。
-
对不起,我看到了,它是正确的,它是我工作源的剪辑版。
-
您必须提供多项选择吗?如果您使用
SelectedObject而不是SelectedObjects,这将非常有效。我正在研究为什么新行现在不起作用。 -
是的,有多个选择可用,我需要所有选定的对象,因为必须可以同时更改所有选定对象的值。它工作正常,但当我选择新行时不行。
-
发生这种情况的原因实际上非常简单 - 在新行提交之前不存在任何数据绑定项。不过仍在尝试寻找解决方案,目前正在尝试使用 BindingSource 以查看是否有帮助。
标签: c# data-binding datagridview