This code works fine except multiple dialog box prompt when there are multiple empty textbox but I only want it to prompt once.
For example, if I enter 1,1,(null),(null),d,g, dialog box will prompt twice since there is two empty textboxes but I only need it to prompt once.
How can I solve this problem?
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.");
}
}
}
You can simply introduce a flag:
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e)
{
bool hasEmpty = false;
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
hasEmpty = true;
}
}
if (hasEmpty) {
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
}
}
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).
Either use a flag, or use Linq.
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e) {
bool flag = false;
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
flag = true;
break;
}
}
if (flag)
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
}
I don't know enough of the used objects to offer a linq solution
Following way should work for you even if your BeforeSave method is getting called multiple times.
private bool _isMessageBoxShown;
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()))
{
if(!_isMessageBoxShown)
{
_isMessageBoxShown = true;
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
break;
}
}
}
}
Just make sure that when you want your messagebox to be shown next time, you will need to set _isMessageBoxShown = false;.
I found out another way to solve it.
public void BeforeSave(BCE.AutoCount.Invoicing.Sales.SalesOrder.SalesOrderBeforeSaveEventArgs e)
{
int tt = 0;
for (int i = 0; i < e.MasterRecord.DetailCount; i++)
{
if (tt == 0)
{
if (String.IsNullOrEmpty(e.MasterRecord.GetDetailRecord(i).YourPONo.ToString()))
{
MessageBox.Show("You left Your PO No empty. Please check it carefully.");
tt = 1;
}
}
}
}
Related
I have an array of toggles defined in script. They are all turned off in the beginning. When the user clicks on one of the toggles, that toggle should be turned on and the other toggles should be switched to off state. Basically there could be only "one" on state toggle. How do I achieve this?
Currently with this script, all the toggles are getting turned off when the user clicks on one of it.
public Toggle[] toggle;
void Start () {
for (int i = 0; i < toggle.Length; i++) {
int idx = i;
toggle[idx].onValueChanged.AddListener (delegate {
ToggleValueChanged (toggle[idx], idx);
});
}
}
public void ToggleValueChanged (Toggle change, int index) {
for (int i = 0; i < toggle.Length; i++) {
if (i == index) {
return;
} else {
if (toggle[i].isOn) {
toggle[i].isOn = false;
}
}
}
}
Unity has a component called ToggleGroup that allow you to do just that.
ToggleContainer Parent Object:
Reference ToggleGroup object in every Toggle component as following:
Scene Hierarchy:
Overview:
https://gfycat.com/bossyscenteddorado
Change your ToggleValueChanged function like this :
public void ToggleValueChanged (Toggle change, int index)
{
for (int i = 0; i < toggle.Length; i++)
{
if (i == index) continue;
if (toggle[i].isOn) {
toggle[i].isOn = false;
}
}
}
When you return in you first if statement, other toggles won't get off. you have to continue iterating your loop.
And instead getting the index and passing it to the delegate, you can use RefrenceEqual
EDIT
Actually each time you manipulate the toggle[i].isOn, you are changing the value of it. So each time, You are calling your function.
EDIT
try this :
public void ToggleValueChanged (Toggle change, int index)
{
for (int i = 0; i < toggle.Length; i++)
{
if (i == index) continue;
if (toggle[i].isOn)
{
toggle[i].SetIsOnWithoutNotify(false);
}
}
}
Why do you even need the index for this?
Simply do
public void ToggleValueChanged (Toggle change)
{
// add a little safety to actually only disable all others if
// this one ws actually enabled
if(!change.isOn) return;
foreach(var toggle in toggles)
{
if (toggle == change) continue;
if (toggle.isOn)
{
// I would actually specifically NOT use "SetIsOnWithoutNotify"
// because you never know who else is actually listening to the state change
// so if you simply set it to false but don't invoke the callback events
// things might behave different than expected
toggle[i].isOn = false;
}
}
}
and accordingly
foreach(var t in toggle)
{
var currentToggle = t;
currentToggle .onValueChanged.AddListener(value => ToggleValueChanged(currentToggle));
}
There is no need to either return or continue, just don't handle the toggle if it's the indexth one:
public void ToggleValueChanged (Toggle change, int index)
{
for (int i = 0; i < toggle.Length; i++)
{
if (i != index)
{
toggle[i].isOn = false;
}
}
}
Also you can assume that all others are off, so no reason to check that either.
If they are mutually exclusive, they aren't "boolean states", it's just one state, supported by an enum and including the null value. If your UI is a set of checkboxes, you should switch it to a set of radio buttons. A dropdown box would do as well.
I'm trying to simulate a user pressing ctrl down, the main goal would be in a datagridview when I select something programarly (initially) I dont want the user to then change that selection if not just add on to it or subtract, just as if you were to hold ctrl + left mouse click. I have no idea where to even begin. I tried to create a selection change event conbined with logicals but that will cause an infinite loop since we would be selecting one by a user then the code change other and other etc infinitely triggering that event. Please help, I'm sort of new to coding. I also don't know how to determine whether a ctrl key has been pressed, is pressed and being held.
private void selecttionh(object sender, EventArgs e)
{
if (stage == "4A" || stage == "3B" && ModifierKeys.HasFlag(Keys.Control))
{
int nothing = 0;
btnclickercl bt = new btnclickercl();
bt.dataGridView1_SelectionChanged(sender, e, dataGridViewReslist, dataGridViewnewres, nothing);
}
if (stage == "4A" || stage == "3B" && (ModifierKeys & Keys.Control) != Keys.Control)
{
MessageBox.Show("Please Press and hold " + "'ctrl'" + " to continue");
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
else
{
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
}
The way to make this happen is to store the selection state separately, update it when the user clicks a cell, then re-apply it. This prevents the selection from being lost every time they click. If you hook the proper event handlers (mouseup, not click) you can do this without the screen flickering and otherwise being a mess to look at.
Everything you need is in this class, including an extension method SetupToggledSelectionMode(), which is your entry point.
static public class Example
{
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new bool[rowCount][];
for (var r = 0; r < rowCount; r++)
{
result[r] = new bool[columnCount];
for (var c = 0; c < columnCount; c++)
{
var cell = input.Rows[r].Cells[c];
result[r][c] = cell.Selected;
}
}
return result;
}
static private void SetSelectionState(DataGridView input, bool[][] selectionState)
{
for (int r = 0; r <= selectionState.GetUpperBound(0); r++)
{
for (int c = 0; c <= selectionState[r].GetUpperBound(0); c++)
{
input.Rows[r].Cells[c].Selected = selectionState[r][c];
}
}
}
static public void SetupToggledSelectionMode(this DataGridView input)
{
bool[][] selectionState = GetSelectionState(input); //This will be stored in a closure due to the lambda expressions below
input.CellMouseUp += (object sender, DataGridViewCellMouseEventArgs e) =>
{
selectionState[e.RowIndex][e.ColumnIndex] = !selectionState[e.RowIndex][e.ColumnIndex];
SetSelectionState(input, selectionState);
};
input.SelectionChanged += (object sender, EventArgs e) =>
{
if (selectionState != null)
{
SetSelectionState(input, selectionState);
}
};
}
}
To use, populate your gridview, set up the initial selection programmatically, and call it like this:
myDataGrid.DataSource = myData;
myDataGrid.Refresh();
myDataGrid.SelectAll();
myDataGrid.SetupToggledSelectionMode();
The SetupToggledSelectionMode() method will register the necessary event handlers and store the selection state of the grid in a closed variable accessible to both handlers. So you won't have to declare anything additional; just call the method.
Thank you for this, this really helped me. all I did was to make it more efficient.Since it would call the Selection change every step of the way, so I got rid of that event completely and only kept the CellMouseup Event.
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new List<int[]>();
for (var r = 0; r < rowCount; r++)
{
for (var c = 0; c < columnCount; c++)
{
if(input.Rows[r].Cells[c].Selected==true)
{
result.add(new int[]{r,c});//will keep only the integer of selected items
}
}
}
return result;//this for me was a recycled variable it can be used or recycled from somewhere else
}
private void SetSelectionState(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
input.Rows[result[i][0]].Cells[result[i][1]].Selected = true;
}
}
public void SetupToggledSelectionMode(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
if(result[i].SequenceEqual(new int[] { e.RowIndex, e.ColumnIndex }))
{
result.RemoveAt(i);
continueer = 1;
break;
}
}
if (continueer == 0)
{
ResRoomSelections.Add(new int[] { e.RowIndex, e.ColumnIndex });
}
SetSelectionState(input);
//whatever else you need to do
}
I know there is still a better way to search List but I could not get a lamda search to work so I just used brute force
-Thank you John Wu for all
I have a timer event that does several things. One item I am trying to get it to do is to programmatically remove the CheckListBox items that are checked once the timer hits the completed action I am performing.
This is the code for the timer and what I have tried to do.
private void timer1_Tick(object sender, EventArgs e)
{
string s;
if (DbFirmwareUpdateComplete.WaitOne(1))
{
DbFirmwareUpdateComplete.Reset();
mnuLoadKeyFile.Enabled = true;
}
if (DbUpdateComplete.WaitOne(1))
{
DbUpdateComplete.Reset();
mnuLoadKeyFile.Enabled = true;
btnLoad.Enabled = true;
}
if (CacheComplete.WaitOne(1))
{
CacheComplete.Reset();
btnLoad.Enabled = true;
}
if (UpdateRunning)
{
bool UpdateDone = true;
int StillActive = 0;
// loop through all active jobs to check if all have completed
foreach (clsCnaPair cna in ActiveJobs)
{
if (cna.Job.JobComplete == false)
{
UpdateDone = false;
StillActive++;
}
else
{
if (cna.Job.UpdateSuccess)
{
// Update color of CLB.Items.Selected if success.
int count = CLB.Items.Count;
for (int index = count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
}
}
}
else
{
// Update color of CLB.Items.Selected if failed.
}
}
}
if (UpdateDone)
{
UpdateRunning = false;
log("All Update jobs have finished.");
}
if (ckTop.Checked == true)
{
ckTop.Checked = false;
}
else
{
ckTop.Checked = false;
}
When I run the program and it hits this piece;
if (cna.Job.UpdateSuccess)
{
// Update color of CLB.Items.Selected if success.
int count = CLB.Items.Count;
for (int index = count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
}
}
}
I get an error:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '-1' is not valid for 'index'.
Parameter name: index
The Error occurs after this piece of code;
private void CLB_SelectedIndexChanged(object sender, EventArgs e)
{
// One of the CNA IPs was selected. sender is the CheckedListBox.
// Here we want to display its fingerprint in the text box, or if the push is running, the status.
// get the CnaPair class represented by this IP:
clsCnaPair CnaPair = (clsCnaPair)CLB.Items[CLB.SelectedIndex];
// Display the corresponding fingerprint string in the editBox:
if (CnaPair.Job != null) txtStatus.Text = CnaPair.Job.GetStatus();
else txtStatus.Text = CnaPair.GetInfo();
}
Or more specifically at the line:
clsCnaPair CnaPar = (clsCnaPair)CLB.Items[CLB.SelectedIndex];
What am I missing? Searching google, shows the way I am doing the remove is consistent with the examples found there.
Thanks,
It's dangerous to modify the contents of the ChecklistBox inside a loop when the loop conditions depend on the contents of the ChecklistBox. Once you call RemoveAt(), the CheckedItems list and the CLB.Items.Count has changed and you will have a problem. In this case, the loop fired the SelectedIndexChanged() event with an invalid Index (-1).
Better to do this in a do-while loop:
bool done;
do
{
done = true;
for (int index = CLB.Items.Count; index > 0; index--)
{
if(CLB.CheckedItems.Contains(CLB.Items[index-1]))
{
CLB.Items.RemoveAt(index - 1);
done = false;
break;
}
}
}while(!done);
This way, every time an item is removed, you break out and start the loop all over again.
After some experimentation, I commented out the CLB_SelecteIndexChanged code and it now completes with the original code.
That leaves one issue. What is the work around with the CLB_SelectedIndexChanged code left in. I will work on that one more and see f I can figure it out with what you guys have provided.
Thanks to both m.rogalski and mcNets.
I have been trying to work out why my background worker is 'finishing' its work when there is still a lot for it to do. I am actually in the process of refactoring the code for this app, so it did work in the past, but now I am unable to figure out what has gone wrong.
Specifically, the app should open Outlook and then perform a few checks. However, the background worker exits straight after Outlook is opened for no apparent reason (as you will se below there is still plenty of processing to be done).
This appears to be happening early on in the Start() method, directly after calling Process.Start() on Outlook.exe.
The code runs in this order:
calling the background worker - this was the user's choice from a radio set
....
else if (radioButton5.Checked == true)
{
textBox1.Text = "Please wait while your session restarts";
pageControl1.SelectedIndex = 10;
backgroundReset.RunWorkerAsync();
}
The do-work method
public void backgroundReset_DoWork(object sender, DoWorkEventArgs e)
{
backgroundReset.WorkerSupportsCancellation = true;
Session.Reset();
}
the reset session method starts by killing the current session ...
public static void Reset()
{
KillSession();
System.Threading.Thread.Sleep(5000);
Start();
// THE BACKGROUNDWORKER EXITS BEFORE HERE!
if (IsLoggedIn() == false)
{
return;
}
else
{
// Make sure Lync is open before finishing the process ...
var j = 0;
GetSession(Init.servers);
j = 0;
var checker = false;
checker = ProcessHandler.CheckRunning("lync.exe");
while (checker == false)
{
if (j == 100)
{
break;
}
Thread.Sleep(500);
checker = ProcessHandler.CheckRunning("lync.exe");
j++;
}
}
}
As you can see from the comment, the backgroundworder is calling RunWorkerCompleted way before the Reset() method has finished executing.
Below are the other methods called (kill, logoff, start):
KillSession logs the session of and then makes sure it is logged off
private static void KillSession()
{
if (sessionId != null)
{
LogOff();
for (int i = 0; i < 150; i++)
{
if (IsLoggedIn() == true)
{
Thread.Sleep(500);
}
else
{
break;
}
}
}
}
LogOff sends a Cmd command to log off the current session
public static void LogOff()
{
string strCmdIn = "/C LOGOFF " + sessionId + " /SERVER:" + serverName;
Cmd.Exec(strCmdIn);
}
Start() Simply opens Outlook, causing a Citrix session to also start. The app is definitely launching Outlook, but after that it doesn't reach either of the for statements - the BackgroundWorker just exits.
public static void Start()
{
Process.Start(appDataCitrix + "Outlook.exe");
for (int i = 0; i < 15; i++)
{
if (IsLoggedIn2() == false)
{
Thread.Sleep(1000);
}
else
{
break;
}
}
if (IsLoggedIn2() == false)
{
Process.Start(appDataCitrix + "Outlook.exe");
for (int i = 0; i < 10; i++)
{
if (IsLoggedIn2() == false)
{
Thread.Sleep(1000);
}
else
{
break;
}
}
}
}
Does anyone have any idea what is going on here? It is driving me crazy!
Many thanks
Update
The RunWorkerCompleted Method:
As far as my understanding goes, this has no baring on when the process will finish.
public void backgroundReset_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (Session.IsLoggedIn())
{
btnFailFinish.Visible = true;
label10.Text = Session.serverName;
pageControl1.SelectedIndex = 3;
}
else
{
pageControl1.SelectedIndex = 10;
pictureBox2.Visible = false;
textBox1.Text = "Double-click Outlook on your desktop to launch a new session.";
textBox15.Text = "Once you have done this please click Finish.";
pictureBox9.Visible = true;
}
}
This is probably because of an exception being thrown from within the start method.
You may either add a try / catch block all around this method and handle the error from within the catch, or check in the RunWorkerCompleted method if an exception occurred :
private void RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
// handle your exception here
}
}
Problem solved.
The original "private void buttonSave_Click" was changed to:
private void buttonSave_Click(object sender, EventArgs e)
{
if (MusicCollection.FormMain.PublicVars.AlbumList.Count != 100)
{
MusicCollection.FormMain.PublicVars.AlbumList.Add(new Album(NameTextBox.Text));
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Original Post:
I'm new to using C#, so appologies for any seemly obvious mistakes or terrible coding.
I'm trying to create a new Album object (that gets its Name from NameTextBox.Text on Form FormAlbumAC) and add it to List AlbumList when the user clicks the save button on FormAlbumAC. Then I want to list all of AlbumList in a ListBox on Form FormMain.
When I run the program and click the save button, I'm getting the error "ArgumentOutOfRangeException was unhandled, Index was out of range" at the line:
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
// line 8 on my excerpt from Form FormAblumAC
I'm not sure what I'm doing wrong. Any help would be much appreciated, thank you.
Form FormMain:
public const int MAX_ALBUMS = 100;
public int totalAlbums = 0;
public FormMain()
{
InitializeComponent();
}
public static class PublicVars
{
public static List<Album> AlbumList { get; set; }
static PublicVars()
{
AlbumList = new List<Album>(MAX_ALBUMS);
}
}
public ListBox AlbumListBox
{
get
{
return AlbumListBox;
}
}
public void ListAlbums(IList list)
{
list.Clear();
foreach (var album in PublicVars.AlbumList)
{
if (album == null)
continue;
list.Add(album.Name);
}
}
Form FormAlbumAC:
private FormMain formMain;
private void buttonSave_Click(object sender, EventArgs e)
{
int index = -1;
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
{
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
{
index = i;
break;
}
}
if (index != -1)
{
MusicCollection.FormMain.PublicVars.AlbumList[index] = new Album(NameTextBox.Text);
++formMain.totalAlbums;
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Your problem (from your comments) is that your for loop's condition is incorrect. Your for loop is this:
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
There is one problem and one potential problem here. First, when this code is actually run, it's really running:
for (int i = 0; i < 100; ++i)
because MusicCollection.FormMain.MAX_ALBUMS is declared as 100. This causes an error when the length of MusicCollection.FormMain.PublicVars.AlbumList is less than 100, because you're trying to grab an index that doesn't exist.
Instead, you need to iterate from i=0 to the length of ....PublicVars.AlbumList-1, or, preferably, for(int i = 0; i < ....PublicVars.AlbumList.Count; i++).
The second potential problem is that you are potentially skipping index 0. Arrays start at index zero and continue to index length-1. As such, you probably want i++, not ++i. Depends on your implementation, though.