两个listbox添加和删除items
#region 添加/移除
//添加
private void btnAdd_Click(object sender, EventArgs e)
{
if (listboxA.Items.Count <= )
{
return;
}
this.AddItems(listboxB, listboxA.SelectedItems);
this.RemoveItems(listboxA, listboxA.SelectedItems);
//UpdateListViewHandler();//调用委托,更新原列表 刷新MainForm窗体
}
//移除
private void btnRemove_Click(object sender, EventArgs e)
{
if (listboxB.Items.Count <= )
{
return;
}
this.AddItems(listboxA, listboxB.SelectedItems);
this.RemoveItems(listboxB, listboxB.SelectedItems);
//UpdateListViewHandler();//调用委托,更新原列表 刷新MainForm窗体
}
/// <summary>
/// 向一个ListBox中添加Items
/// </summary>
/// <param name="lstBox"></param>
/// <param name="items"></param>
private void AddItems(UI.ListBoxEx lstBox, IEnumerable items)
{
DataTable dt = null;
foreach (object item in items)
{
if (item is DataRowView)
dt = ((DataRowView)item).Row.Table.Clone();
if (item is DataRow)
dt = ((DataRow)item).Table.Clone();
break;
}
if (lstBox.DataSource != null)
dt = ((DataTable)lstBox.DataSource).Copy();
foreach (object item in items)
{
if (item is DataRowView)
dt.Rows.Add(((DataRowView)item).Row.ItemArray);
if (item is DataRow)
dt.Rows.Add(((DataRow)item).ItemArray);
}
lstBox.DataSource = dt;
if (this.Text.Contains("Add or Remove Exc"))
{
lstBox.DisplayMember = "ExcName";
lstBox.ValueMember = "ExcID";
}
else if (this.Text.Contains("Add or Remove Cs"))
{
lstBox.DisplayMember = "CsName";
lstBox.ValueMember = "CsID";
}
}
/// <summary>
/// 从一个ListBox中删除Items
/// </summary>
/// <param name="lstBox"></param>
/// <param name="items"></param>
private void RemoveItems(UI.ListBoxEx lstBox, IEnumerable items)
{
DataTable dt = ((DataTable)lstBox.DataSource);
DataTable newDt = dt.Clone();
bool flag = false;
//因为直接删除DataRow会保存,所以用这样丑陋的方式处理了
foreach (DataRow dr in dt.Rows)
{
foreach (DataRowView item in items)
{
if (dr == item.Row)
{
flag = true;
break;
}
else
flag = false;
}
if (!flag)
newDt.Rows.Add(dr.ItemArray);
else
continue;
}
lstBox.DataSource = newDt;
if (this.Text.Contains("Add or Remove Exc"))
{
lstBox.DisplayMember = "ExcName";
lstBox.ValueMember = "ExcID";
}
else if (this.Text.Contains("Add or Remove Cs"))
{
lstBox.DisplayMember = "CsName";
lstBox.ValueMember = "CsID";
}
}
#endregion