将新DataSource追加到DataGridView中的现有DataSource



我想将List<T>附加到DataGridView的现有DataSource。实现这一目标的最佳方式是什么?

下面是我尝试的代码示例。

var acList = new List<Account>();
for (int i = 0; i < gridAcearch.Rows.Count; i++)
{
if (Convert.ToBoolean(gridAcearch.Rows[i].Cells[0].Value) == true)
{
try
{
string accountId = gridAcearch.Rows[i].Cells["accountIds"].Value.ToString();
acList.Add(db.Accounts.Where(x => x.accountId == accountId).FirstOrDefault());
}
catch { }
}
}
if (gridOpenBalance.Rows.Count <= 1)
{
bindS = new BindingSource();
bindS.DataSource = acList;
var source = new BindingSource(bindS, null);
gridOpenBalance.DataSource = source;
}
else
{
//here I want to add new aclist to the existing one in the grid ,
//if I added it immediately the previous rows in the grid gets deleted and new ones gets added
//I used this code but it doesn't work , If there something like

var bindS = new BindingList<Account>(acList)
var source = gridOpenBalance.DataSource;
//if there is something work this way  

bindS.DataSource = acList + gridOpenBalance.DataSource;
bindS.DataSource = acList;
source = new BindingSource(bindS, null);
gridOpenBalance.DataSource = source;
}

我会尝试这样的东西:

  • 生成一个类属性private List<Account> dataList = new List<Account>();
  • 将您的结果添加到该列表中
  • 使用dataGridView1.Rows.Clear();dataGridView1.Refresh();清除视图
  • 加载dataList作为新源

这可能效率低下,但可能有助于你摆脱困境。

最新更新