Why not break out of the loop so that it stops checking?
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e)
{
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
break; // <--
}
}
}
return will also work in this situation.
Test if BeforeSave is running twice:
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e)
{
MessageBox.Show("Test"); // <--
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
break; // <--
}
}
}
As yo can see I added a new "Test" message at the top of the method (outside the loop), if you see duplicate "Test" messages when using the code, it means that BeforeSave is running twice.
In that case you need to look at why it is running twice, and then fix that. If that is not fixable, then there could be some syncronization solution... such as:
private int canSave;
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e)
{
if (Interlocked.CompareExchange(ref canSave, 0, 1) != 1)
{
// Any cancelation logic that's appropiate here
return;
}
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
break; // <--
}
}
}
Then you see canSave 1 to allow the code to run 0 to disallow it. The Interlocked operation will ensure that the code in BeforeSave will not run again until you set canSave to 1 somewhere in the code (it automatically sets it to 0 when it gets executed - no chance for multiple threads to mess it up).
Although I'm giving you a solution to control double execution of BeforeSave, if it is running twice than expected shows that there is some problem somewhere else, and you should be trying to fix that (unless it is third party code).