尝试使用BindingList类型的数据源向Infragistic UltraWinGrid添加新行时出现以下错误:
无法添加行:类型' System.String'上的构造函数找不到
通过网格删除项目工作正常但是,尝试使用网格底部的添加新行时会出现上述错误。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
namespace BindingListChangedEvent
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private BindingList<string> shoppingList;
private void FrmMain_Load(object sender, EventArgs e)
{
//let's just add some items to the list
string[] items = { "Rice", "Milk", "Asparagus", "Olive Oil", "Tomatoes", "Bread" };
shoppingList = new BindingList<string>(items.ToList());
shoppingList.AllowNew = true; //if this is not set error: "Unable to add a row: Row insertion not supported by this data source" is thrown
ugList.DataSource = shoppingList;
shoppingList.ListChanged += new ListChangedEventHandler(ShoppingList_ListChanged);
}
public void ShoppingList_ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString()); //what happened to the list?
}
private void ugList_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
{
e.Layout.Override.CellClickAction = CellClickAction.RowSelect;
e.Layout.Override.AllowDelete = DefaultableBoolean.True;
e.Layout.Override.AllowAddNew = AllowAddNew.TemplateOnBottom;
}
private void btnAddCookies_Click(object sender, EventArgs e)
{
shoppingList.Add("Cookies");
ugList.Refresh();
}
}
我尝试添加一个按钮来手动将项目添加到列表中而不涉及UltraWinGrid(btnAddCookies_Click),这没有问题。
有什么想法可以帮助我朝着正确的方向前进?感谢
答案 0 :(得分:0)
BindingList<string>
AllowNew
到true
会导致绑定列表通过反射创建新项目。 bindinglist的作用是通过反射实例化generictype(在本例中为string)。这也是导致异常的原因。因为字符串valuetype没有任何构造函数。将自己创建的类型与构造函数绑定肯定是可能的。在这种情况下,您可以创建一个包装类:
public class MyList
{
public string ListItem { get; set; }
public MyList( string listItem )
{
ListItem = listItem;
}
}
并绑定此类:BindingList<MyList> bindingList = new BindingList<MyList>();