{again} C# MessageBox created more than once - c#

I have a similar question as last time, but no matter how much I hit my head against the wall, solution is not coming. The problem is that the message box gets created too many times, when it should only open once, unsubscribe from documentCompleted and then exit. Thanks again!
private void textBox4_TextChanged(object sender, EventArgs e)
{
if (textBox4.Text.Length >= 3)
{
timer1.Enabled = true;
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if (textBox4.Text != "")
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://worldofwarcraft.com/en-gb/search?q=" + textBox4.Text);
webBrowser1.DocumentCompleted += GetImg; //sub here
}
}
private void GetImg(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string img_url = "";
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
{
if (el.GetAttribute("className") == "Avatar-image")
{
img_url = (el.OuterHtml).Substring(el.OuterHtml.IndexOf("https"));
img_url = img_url.Substring(0, img_url.IndexOf(")"));
pictureBox1.ImageLocation = img_url;
}
else if (el.GetAttribute("className") == "Character-level")
{
textBox5.Visible = true;
label7.Visible = true;
string lvl_url = "";
lvl_url = (el.InnerHtml).Substring(3);
lvl_url = lvl_url.Substring(0, lvl_url.IndexOf("<"));
textBox5.Text = lvl_url;
DialogResult YESNO = MessageBox.Show("Is this your character?", "Select your char", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (YESNO == DialogResult.Yes)
{
// clean up
webBrowser1.DocumentCompleted -= GetImg; //unsub here
pictureBox1.Enabled = false;
timer1.Dispose();
break;
}
}
}
}

You need to either set timer1.Enabled to false or call timer1.Stop() as soon as you enter the timer1_Tick_1 method, or the timer will keep firing and calling your method every time.

Related

Updating/Deleting a row in listview that includes a countdown timer

Currently i am having trouble updating a row in my listview that contains both text and a timer that counts down. So far I've tried updating the entire row as well as trying to update just the text and i get an error in each instance.
System.ArgumentOutOfRangeException: InvalidArgument=Value of '0' is not valid for 'index
I am also having a slight problem with the delete button. It deletes the row as planned but it appears the information is still running in the background and haven't come across any info on how to delete the session. I pray for your guidance.
private void Confirm_Click(object sender, EventArgs e)
{
CSession newSession = new CSession();
if(PasswordText.Text == "")
{
MessageBox.Show("Password not entered");
return;
}
newSession.password = PasswordText.Text;
newSession.purchased_time = workingTimeSpan;
newSession.remaining_time = workingTimeSpan;
newSession.status = "Online";
sessionlist.Add(newSession);
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void DisplayAllSessions()
{
listView1.Items.Clear();
foreach(CSession c in sessionlist)
{
string[] row = { c.password, c.purchased_time.ToString(), c.remaining_time.ToString(), c.status };
ListViewItem i = new ListViewItem(row);
listView1.Items.Add(i);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach(CSession c in sessionlist)
{
if (c.remaining_time.TotalMinutes == 5 && !c.MessageDisplayed)
{
c.MessageDisplayed = true;
MessageBox.Show("Time almost up for client.");
}
if (c.remaining_time.TotalSeconds < 1)
{
c.status = "Offline";
}
if(c.status == "Online")
{
c.remaining_time -= oneSecond;
}
}
DisplayAllSessions();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void Reset_Click(object sender, EventArgs e)
{
}
private void updatebutton()
{
listView1.SelectedItems[0].SubItems[0].Text = PasswordText.Text;
PasswordText.Text = "";
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
PasswordText.Text = listView1.SelectedItems[0].Text;
TimerLabel.Text = listView1.SelectedItems[0].SubItems[1].Text;
}
private void Delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you wish to delete.", "Removing User", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
listView1.Items.Clear();
timer1.Stop();
}
}
This is what i used for the update function and delete row function.
private void updatebutton()
{
CSession updatedsession = new CSession();
int updateindex = 0;
int index = 0;
foreach (CSession lookup in sessionlist)
{
if(lookup.password == PasswordText.Text)
{
if (MessageBox.Show("Do you wish to add time.", "Adding Time",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
updatedsession = lookup;
updateindex = index;
}
break;
}
index++;
}
updatedsession.purchased_time = workingTimeSpan +
updatedsession.purchased_time;
updatedsession.remaining_time = workingTimeSpan +
updatedsession.remaining_time;
sessionlist[updateindex] = updatedsession;
//sortedSessionList[PasswordText.Text] = updatedsession;
PasswordText.Text = "";
TimerLabel.Text = "";
workingTimeSpan = new TimeSpan();
}
private void Update_Click(object sender, EventArgs e)
{
updatebutton();
}
private void Delete_Click(object sender, EventArgs e)
{
CSession cSession = new CSession();
if (MessageBox.Show("Do you wish to delete.", "Removing User",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
int index = 0;
foreach (CSession c in sessionlist)
{
if(c.password == PasswordText.Text)
{
break;
}
index++;
}
sessionlist.RemoveAt(index);
}
}

Visual Studio won't open my new form

I'm having a tiny issue here.. It's a little annoying.. I can't debug my application because of this..
My problem is.. When I try to open a new form automatically by code. It will not open other form. But when you click the button yourself on the form. It will open.. And I think this is a little weird.. Because it uses the same code...
Here is my button code that opens the new form(And it works great.):
private void button1_Click(object sender, EventArgs e)
{
label4.Text = "Login in... Please wait.";
Properties.Settings.Default.username = usernameText.Text;
if (checkBox1.Checked == true)
{
Properties.Settings.Default.check1 = true;
Properties.Settings.Default.password = passwordText.Text;
if (checkBox2.Checked == true)
{
Properties.Settings.Default.check2 = true;
}
}
Properties.Settings.Default.Save();
button1.Enabled = false;
checkBox1.Enabled = false;
checkBox2.Enabled = false;
startLoginWorker();
}
Here is the other code that opens it automatically:
private void loginForm_Load(object sender, EventArgs e)
{
String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
String gpsPath = appDataFolder + "/GameProfileSaver";
label4.Text = "Checking files...";
if (!File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll") || !File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll"))
{
//startDownload("dll");
button1.Enabled = true;
}
else
{
button1.Enabled = true;
label4.Text = "File check complete. Ready for login.";
progressBar1.Value = 100;
}
if (checkBox2.Checked == true)
{
button1.PerformClick();
}
The "button1.PerformClick()" Just clicks the button by code right? Shouldn't be any difference....
And I have even tried to just put that code into that if statement.. Still nothing.
This is the code that gets run out of it all:
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(oppenMainForm));
t.SetApartmentState(ApartmentState.STA);
t.Start();
Openmainform:
private void oppenMainForm()
{
Application.Run(new Form1(usernameText.Text));
}
If anyone have any suggestions... Please help me... It's frustrating.

Deleting items from listbox raises exception

I need to be able to delete items from a listbox but when I press the delete function and say yes I want to delete I get this exception: Items collection cannot be modified when the DataSource property is set.
Now I want to know what to do about this.
namespace Flashloader
{
public partial class Form1 : Form
{
private controllerinifile _controllerIniFile;
private toepassinginifile _toepassingIniFile;
// private Toepassinglist _toepassingList;
private StringList _comPorts;
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
button4.Visible = false;
_controllerIniFile = new controllerinifile();
_toepassingIniFile = new toepassinginifile(_controllerIniFile.Controllers);
// _toepassingList = new Toepassinglist(_controllerList).FromIniFile();
_comPorts = new StringList();
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
_applicationListBox.Refresh();
_controllercombobox.Refresh();
Settings settings = _toepassingIniFile.Settings;
textBox3.Text = settings.Port;
textBox4.Text = settings.Baudrate;
}
// File select Button and file directory
private void button2_Click(object sender, EventArgs e)
{
appfile.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
{
if (appfile.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = appfile.FileName;
appfile.Title = ("Choose a file");
appfile.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), #"C:\\\\Projects\\flashloader2013\\mainapplication\\");
textBox1.Text = string.Format("{0}", appfile.FileName);
}
// textbox for the bootfile
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
// start button for sending appfiles
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
serialPort1.Open();
if (MessageBox.Show(appfile.FileName + " is selected and ready to be send,Are you sure you want to send the selected file?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The selected file will not be send.", "", MessageBoxButtons.OK);
}
else
{
button1.Visible = false;
button4.Visible = true;
}
try
{
using (FileStream inputstream = new FileStream(OpenBoot.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 32 * 1024 * 1024, FileOptions.SequentialScan))
{
byte[] buffer = new byte[8 * 1024 * 1024];
long bytesRead = 0, streamLength = inputstream.Length;
inputstream.Position = 0;
while (bytesRead < streamLength)
{
long toRead = streamLength - bytesRead;
if (toRead < buffer.Length)
buffer = new byte[(int)toRead];
if (inputstream.Read(buffer, 0, buffer.Length) != buffer.Length)
throw new Exception("File read error");
bytesRead += buffer.Length;
serialPort1.Write(buffer, 0, buffer.Length);
}
}
}
catch
{
MessageBox.Show("No file selected");
}
StringList list = new StringList().FromFile(appfile.FileName);
// Read file and put it in a list that will be sorted.
foreach (String line in list)
{
list.Sort();
serialPort1.Write(line);
}
MessageBox.Show("Bootfile and Applicationfile are send succesfully.");
}
// abort button for sending files
private void button4_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
button4.Visible = false;
button1.Visible = true;
progressBar1.Value = 0;
timer1.Enabled = false;
serialPort1.Close();
}
// backgroundworkers
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DateTime start = DateTime.Now;
e.Result = "";
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(50);
backgroundWorker1.ReportProgress(i, DateTime.Now);
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
TimeSpan duration = DateTime.Now - start;
e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
}
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
DateTime time = Convert.ToDateTime(e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void Boot_button_Click(object sender, EventArgs e)
{
OpenBoot.Filter = "Binary Files (.BIN; .md6; .md7)|*.BIN; *.md6; *.md7|All Files (*.*)|*.*";
{
if (OpenBoot.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(appfile.FileName);
sr.Close();
}
}
String filedata = OpenBoot.FileName;
OpenBoot.Title = ("Choose a file");
OpenBoot.InitialDirectory = "C:\\Projects\\flashloader2013\\mainapplication\\Bootfiles";
textBox2.Text = string.Format("{0}", OpenBoot.FileName);
}
// Saving the settings to the INI file.
private void SaveSettings()
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
MessageBox.Show("No Application selected");
return;
}
toepassing.Controller = (Controller)_controllercombobox.SelectedItem;
toepassing.Lastfile = textBox1.Text;
// toepassing.TabTip =
_toepassingIniFile.Save();
}
private Controller GetCurrentController()
{
int index = _controllercombobox.SelectedIndex;
if (index < 0)
return null;
return _controllerIniFile.Controllers[index];
}
private Toepassing GetCurrentApplication()
{
int index = _applicationListBox.SelectedIndex;
if (index < 0)
return null;
return _toepassingIniFile.ToePassingen[index];
}
private void typelistbox_SelectedIndexChanged(object sender, EventArgs e)
{
Toepassing toepassing = GetCurrentApplication();
if (toepassing == null)
{
// TODO velden leegmaken
}
else
{
// appfile.InitialDirectory = Path.GetDirectoryName(controller.Lastfile);
appfile.FileName = toepassing.Lastfile;
textBox1.Text = toepassing.Lastfile;
_controllercombobox.SelectedItem = toepassing.Controller;
}
}
private void _controllercombobox_SelectedIndexChanged(object sender, EventArgs e)
{
Controller controller = GetCurrentController();
if (controller == null)
{
// TODO velden leegmaken
}
else
{
textBox2.Text = controller.Bootfile;
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void changeCurrentControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controlleredit = new Controlleredit(_controllerIniFile);
controlleredit.Show();
Refresh();
}
private void addControllerToolStripMenuItem_Click(object sender, EventArgs e)
{
var controllersettings = new Newcontroller(_controllerIniFile);
controllersettings.ShowDialog();
_controllercombobox.DataSource = null;
_controllercombobox.DataSource = _controllerIniFile.Controllers;
// Refresh();
// _controllercombobox.Refresh();
}
private void newapplicationBtton_Click(object sender, EventArgs e)
{
var newapplication = new NewApplication(_toepassingIniFile);
newapplication.ShowDialog();
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
/////////////////////////////The Error is down here /////////////////////////////
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
this._applicationListBox.Items.RemoveAt(this._applicationListBox.SelectedIndex);
}
}
}
The error says it quite clearly: you have to remove the item from the underlying datasource, you can't delete it manually. If you want to remove/add items manually, you shouldn't use databinding but build the list by hand.
As exception say you can't delete items directly from ListBox - you have to remove it from underlying DataSource and then rebind control (if it is not bound to BindingSource for example)
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to delete application: "+ Environment.NewLine + _applicationListBox.SelectedItem +Environment.NewLine + " Are you sure you want to delete the application?", "", MessageBoxButtons.YesNo) == DialogResult.No)
{
MessageBox.Show("The application will not be deleted.", "", MessageBoxButtons.OK);
}
else if (this._applicationListBox.SelectedIndex >= 0)
{
var item = this.GetCurrentApplication();
_toepassingIniFile.ToePassingen.Remove(item);
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = _toepassingIniFile.ToePassingen;
}
}
Your code is hard to read so I was a bit guessing with classes etc, but it should work.
Try to remove from datasource itself as below:
string myobj = this._applicationListBox.SelectedValue.ToString();
data.Remove(myobj );
_applicationListBox.DataSource = null;
_applicationListBox.DataSource = data;
As others have said. You must have a list that is bound to the listbox. You cannot delete from the listbox directly.
You should delete from the List
private Toepassinglist _toepassingList
That is the datasource for your listbox.
Delete the item you want like so...
this._toepassingList.Items.RemoveAt(this._applicationListBox.SelectedIndex);
You can delete from list:---
ListName.Items.RemoveAt(postion);

Groupbox for Windows form

I have created gui for windows form....!
one side i have groupbox with checkbox and two buttons ">>" and "<<" and on the other side i have one more groupbox.
I need to select one checkbox at a time if the user select more than one checkbox i need to raise error..
if the user selects checkbox and click on ">>" button i need to display number of messages in the other groupbox i.e in the "List of Selected Commands"...
and on the click of ">>" the selected list of message should be deleted from list.
I have included tab control in my gui on click of this tab i need to display some list of commands how can i do it...
can any one help me on this...
This is the code..
namespace Menu_Sample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
groupBox1.Text = "MSC";
groupBox2.Text = "List Of Selected Commands";
checkBox1.Visible = false;
cb2.Visible = false;
cb3.Visible = false;
cb4.Visible = false;
label1.Visible = false;
label2.Visible = false;
label3.Visible = false;
label4.Visible = false;
}
private void submenu1ToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox1.Text = "ICP";
checkBox1.Visible = true;
cb2.Visible = true;
cb3.Visible = true;
cb4.Visible = true;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
label1.Visible = true;
label1.Text = "ibit";
groupBox2.Controls.Add(label1);
label2.Visible = true;
label2.Text = "Cbit";
groupBox2.Controls.Add(label2);
label3.Visible = true;
label3.Text = "Kbit";
groupBox2.Controls.Add(label3);
label4.Visible = true;
label4.Text = "ibit";
groupBox2.Controls.Add(label4);
}
if (cb2.Checked == true)
{
label1.Visible = true;
label1.Text = "ibit";
groupBox2.Controls.Add(label1);
label2.Visible = true;
label2.Text = "Cbit";
groupBox2.Controls.Add(label2);
label3.Visible = true;
label3.Text = "Kbit";
groupBox2.Controls.Add(label3);
label4.Visible = true;
label4.Text = "ibit";
groupBox2.Controls.Add(label4);
}
}
private void btn6_Click(object sender, EventArgs e)
{
if (label1.Enabled==true)
{
label1.Text = "";
}
}
private void btn5_Click(object sender, EventArgs e)
{
label1.Text = "";
label2.Text = "";
label3.Text = "";
label4.Text = "";
}
private void submenu2ToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox1.Text = "MCP";
}
private void mDPToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox1.Text = "MDP";
}
private void mRPPToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox1.Text = "MRPP";
}
}
}
I am giving you an idea, that how we can do that.
You have to create a group box click event and then use loop for the controls in that groupbox and if that control is checkbox and it is checked, then you just count that no-other checkbox should be checked.
I will be available with the code very shortly.

C# BackGroundWorker with ProgressBar Updates after process complete

I have the following in a button click event:
private void buttonSubmitAchChecks_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy) return;
SubmittingAch(true);
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
label_Status.Text = "Submitting checks to ACH ....";
var qry = from ds in checkTrans.IndividualCheck
where ds.SubmitToACH &&
ds.Status == "Entered" &&
ds.CheckAmount > 0 &&
ds.SubmitToACH
select ds;
if (qry.Count() <= 0)
{
label_Status.Text = "Nothing to submit. Check the Check Amount, ACH, and Status fields.";
}
else
{
progressBar1.Maximum = qry.Count();
progressBar1.Minimum = 0;
progressBar1.Step = 1;
backgroundWorker1.RunWorkerAsync(qry);
}
}
My backgroundWorker1_DoWork:
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
}
else
{
var qry = e.Argument as EnumerableRowCollection<CheckTrans.IndividualCheckRow>;
if (qry != null)
{
Thread.Sleep(4000);
//item.Status = ach.SubmitCheck(item);
var ach = new SubmitAchChecks();
foreach (var item in qry)
{
ach.SubmitCheck(item);
backgroundWorker1.ReportProgress(1);
Console.Write("backgroundWorker1_dowork=" + progressBar1.Value.ToString() + "\r\n");
}
}
}
}
My Cancel Button:
private void cancelAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
label_Status.Text = "Cancelling...";
backgroundWorker1.CancelAsync();
}
}
My backgroundWorker1_RunWorkerCompleted:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
label_Status.Text = "Canceled!";
}
else if (e.Error != null)
{
label_Status.Text = "Error: " + e.Error.Message;
}
else
{
label_Status.Text = "Done!";
}
SubmittingAch(false);
}
My backgroundWorker1_ProgressChanged:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value += 1;
Console.Write("progressbar1.value=" + progressBar1.Value.ToString() + "\r\n");
}
I get following output in my debug window when I processed 2 items:
backgroundWorker1_dowork=0
backgroundWorker1_dowork=0
progressbar1.value=1
progressbar1.value=2
The event is firing, but as you can see from the console.write, it's happening AFTER the thread finishes. I get the progressbar scrolling, but only once the dowork has completed.
What have I done wrong on this? I'd like it to update as each item is completed.
It's due to the way threads work. ProgressChange is invoked on the UI thread using BeginInvoke, and therefore on another thread. Meanwhile, the worker thread continues running. Since there is not much work to do, the BackgroundWorker finishes its work before BeginInvoke actually invokes the method, because thread switches don't happen every CPU operation. They happen after quite a few. To avoid this, manually call the method that increments the ProgressBar's value using this.Invoke().

Categories

Resources