使用BindingNavigator删除列表项,不正确的项目
我使用BindingNavigator通过datagridview从产品列表中删除项目。 (方法调用main.DeleteProduct()调用一个存储库以从数据库中删除)。使用BindingNavigator删除列表项,不正确的项目
我需要一些帮助来改善..DeleteItem_Click事件的代码。当我单击一个单元格/或行,然后删除按钮(BindingNavigator)时,它从不删除该行。它将删除下面的行,或者如果它是最后一行,则删除上面的行,如果只有一行,则删除null。 bindingSource.Current应该不是与datagridview的currentrow相同的项目吗?
此外,是我使用bindsource铸造当前项目的一种好方法吗?如果有的话,会提供更好的代码建议。
干杯!
public partial class Form1 : Form
{
private MainBL main = new MainBL();
private List<Product> products = new List<Product>
private void Form1_Load(object sender, EventArgs e)
{
bsProducts.DataSource = products; // BindingSource
bnProducts.BindingSource = bsProducts; // BindingNavigator
dataGridView1.DataSource = bsProducts; //
}
private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
{
Product product = (Product)bsProducts.Current;
// Putting a breakpoint here, shows the identity property is not the same
// as row selected in datagridview.
main.DeleteProduct(product);
}
我现在明白该行在CellClick事件触发前被删除。因此,我通过将代码放入删除按钮的_MouseDown事件来使其按预期工作。不知道这是虽然最妥善的解决办法..
private void btnDeleteProducts_MouseDown(object sender, MouseEventArgs e)
{
Product product = (Product)bsProducts.Current;
if (product != null)
{
main.DeleteProduct(product);
}
}
更好的解决方案可能是拦截/删除绑定导航器的删除事件,并手动处理删除。
转到装订导航器;调出属性窗口中的属性。找到DeleteItem属性(位于“Items”类别下),并将其设置为“(none)”。
现在,您可以在相关工具栏中的删除按钮的单击事件中编写删除功能。上一个答案中的代码将起作用 - 您现在可以获取正确的“当前”项目。如果需要,您可以在此添加确认检查(“您确定吗?”)。
当然,不要忘记从BindingSource绑定到的集合中删除项目(或者只是刷新数据)。
我遇到了这个,并做了类似于OP [bretddog]做的事情,但我写了一个更完整的方法。
我在这里分享我的工作:
public class YourDataItem
{
// put all of your data here. This is just stubbed here as an example
public int Id { get; set; }
public String Description { get; set; }
}
private void DeleteBtn_Down(Object sender, MouseEventArgs e)
{
var item = (YourDataItem)bindingSource1.Current;
var dr = DialogResult.None;
if (0 < item.Id)
{
var ask = String.Format("Delete Item [{0}]?", item.Description);
dr = MessageBox.Show(ask, "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
if (dr == DialogResult.Yes)
{
try
{
bindingSource1.EndEdit();
_datamodel.YourDataItems.DeleteOnSubmit(item);
_datamodel.SubmitChanges();
_datamodel.ClearCache();
bindingSource1.SetPosition<YourDataItem>(x => x.Id == 0);
} catch (Exception err)
{
MessageBox.Show("Database changes failed to complete.", String.Format("Delete {0}", err.GetType()), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} else
{
bindingSource1.CancelEdit();
}
}
LINQ的数据源可能会超时。
如果有人在当天回家时碰到删除按钮,则在第二天进入并在确认对话框中单击“确定”,try...catch
将处理对象处置异常。
ClearCache()
仅仅是一个知名的DataContext扩展:
/// <summary>
/// Clears the cache from a DataContext to insure data is refreshed
/// </summary>
/// <param name="dc"></param>
public static void ClearCache(this DataContext dc)
{
dc.GetType().InvokeMember("ClearCache", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, dc, null);
}
这个答案帮我调试同样的问题,我与DataGridView中和DeleteItem功能... – ChenChi 2016-08-29 13:02:22