我绑定了来自DataGridView
的{{1}}。我已经设置了设计师List<T>
。
如果列表为null,我将创建一个空列表,以便显示标题,但它不会为我创建一个空行以便能够添加元素。为什么?如何让用户将值添加到此列表中?
一些代码
Enable adding
答案 0 :(得分:12)
首先,DataGridView.AllowUserToAddRows
必须是true
(因为您在设计师中设置了它)。
该财产说
如果DataGridView绑定到数据, 如果允许用户添加行 这个属性和数据 source的IBindingList.AllowNew 属性设置为true。
IBindingList.AllowNew
(不可设置)也提到:
如果IList.IsFixedSize或 IList.IsReadOnly是真的,这个 property返回false。
由于您绑定了IEnumerable
,我相信IsReadOnly
是false
。尝试将列表公开为List<T>
并绑定到BindingList<T>
。
public List<Value> ValueList
{
get;
set;
}
private void Form1_Load(object sender, EventArgs ev)
{
if (ValueList == null)
{
ValueList = new List<Value>();
}
dataGrid.DataSource = new BindingList<Value>(ValueList);
}
答案 1 :(得分:2)
如果您有DataGridView.AllowUserToAddRows = true,那么该属性将为false;但是没有绑定类的默认构造函数。 添加默认值,它应该工作
public class atsTableInclude
{
// keep this to allow user to add row
public atsTableInclude() { }
public atsTableInclude(string p, bool u)
{
Prefix = p;
Use = u;
}
public string Prefix { get; set; }
public bool Use { get; set; }
}
public Sorting.SortableBindingList<T> FillAtsList<T>(string jsonfile) where T : class
{
if (!File.Exists(jsonfile))
{
MessageBox.Show(jsonfile, "File not found");
return null;
}
try
{
// load json from file
using (StreamReader r = new StreamReader(jsonfile))
{
string json = r.ReadToEnd();
var res = JsonConvert.DeserializeObject<List<T>>(json);
return new Sorting.SortableBindingList<T>(res);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Cannot load json", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
private void frmATS_Load(object sender, EventArgs e)
{
string jsonfile2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "atsTableInclude.json");
dataGridView2.DataSource = FillAtsList<atsTableInclude>(jsonfile2);
}
答案 2 :(得分:0)
添加到Jon的答案:BindingList<T>
有一个事件,AddingRow
,您可以听,以指定要添加的项目:
AddHandler _bindingList.AddingNew, Sub(s, args)
args.NewObject = New TicketItem("dawg")
End Sub