My winform has a progress bar which should increase based on the number of files the program is processing. it works fine on one box (win xp) but not the other(winserver 2008). The bar is not filled fully by the time the process ends. Both have the same .net framework 3.5
private void data_process()
{
int progress_num = (100/checkedListBox1.Items.Count);
.......
progressBar1.Value = progressBar1.Value + progress_num;}
do you know why? and do you have better solution?
------this is the new code
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
richTextBox1.Clear();
richTextBox1.Focus();
if (checkedListBox1.CheckedItems.Count < 1)
{
MessageBox.Show("No file is selected", "Warning");
}
else
{
if ((region != null) && (venue != null) && (lhversion != null) && (release_version != null) && (desc != null))
{
progressBar1.Maximum = checkedListBox1.Items.Count + 3;
progressBar1.Step = 1;
//progressBar1.Value = progressBar1.Value + 10;
progressBar1.PerformStep();
login();
//progressBar1.Value = progressBar1.Value + 10;
progressBar1.PerformStep();
data_process();
//progressBar1.Value = progressBar1.Value + 10;
progressBar1.PerformStep();
if (user_in == true)
{
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.AppendText("Done");
}
}
private void data_process()
{
string line;
//int progress_num = (70/checkedListBox1.Items.Count);
foreach (object itemChecked in checkedListBox1.CheckedItems) // for each selected file
{
...
progressBar1.PerformStep();
}
}
I will try to use the native command to increment the progress bar without calculating the increment
(what happens when the items are > 100?)
progressBar1.Maximum = checkedListBox1.Items.Count;
progressBar1.Step = 1;
...
progressBar1.PerformStep();
Related
I just started with the programming language C# a week ago and used the program Visual Studio with win Forms. I've had a problem for a few days.
I want to connect a ProgressBar to different TextBoxes. So that with each filled textBox the ProgressBar increases. When the text is removed, the progressBar should go down again.
So far I've only managed to get the progressBar to increase in general or that the progress bar increases with each letter in a textBox.
Textboxes are Vorname,Nachname,PLZ,Wohnort,Hausnummer,Straße
ProgressBar is Fortschrittsanzeige
private void button1_Click(object sender, EventArgs e)
{
Fortschrittsanzeige.Dock = DockStyle.Bottom;
Fortschrittsanzeige.Maximum = 60;
Fortschrittsanzeige.Minimum = 0;
Fortschrittsanzeige.Style = ProgressBarStyle.Continuous;
if (
Vorname.Text.Length <= 0 ||
Nachname.Text.Length <= 0 ||
PLZ.Text.Length < 4 ||
Wohnort.Text.Length <= 0 ||
Hausnummer.Text.Length <= 0 ||
Straße.Text.Length <= 0
)
{
textBox7.Text = ("Bitte überprüfe deine Eingabe");
}
else
{
Sendebutton.Text = "Gesendet";
textBox7.Text = "Vielen Dank" + Vorname.Text + " " + Nachname.Text + ", wir
haben deine Daten erhalten.";
}
if (Vorname.Text.Length <= 0)
{
Vorname.BackColor = Color.IndianRed;
}
else
{
Vorname.BackColor = Color.White;
Fortschrittsanzeige.Value += 10;
}
if (Nachname.Text.Length <= 0)
{
Nachname.BackColor = Color.IndianRed;
}
else
{
Nachname.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (PLZ.Text.Length < 4)
{
PLZ.BackColor = Color.IndianRed;
}
else
{
PLZ.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Wohnort.Text.Length <= 0)
{
Wohnort.BackColor = Color.IndianRed;
}
else
{
Wohnort.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Hausnummer.Text.Length <= 0)
{
Hausnummer.BackColor = Color.IndianRed;
}
else
{
Hausnummer.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
if (Straße.Text.Length <= 0)
{
Straße.BackColor = Color.IndianRed;
}
else
{
Straße.BackColor = Color.White;
Fortschrittsanzeige.Step += 10;
}
}
You can handle the TextChanged event on each TextBox like so
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0 && _textbox1IsEmpty)
{
progressBar1.Value += 10;
_textbox1IsEmpty = false;
}
else if (textBox1.Text.Length <= 0)
{
progressBar1.Value -= 10;
_textbox1IsEmpty = true;
}
}
and add a private property in your class
private bool _textbox1IsEmpty = true;
You can make a function to optimize it and don't have duplicate code
Here are a few tips to get you started with WinForms and make it easier to connect multiple TextBoxes with a ProgressBar.
The textboxes (and other controls) that are on a Form can be found in the Controls collection of the form.
All of the textboxes on the form can be obtained with a simple query.
For example, in the form Constructor you could go though all the textboxes and attach a TextChanged handler to each.
public MainForm()
{
InitializeComponent();
foreach (TextBox textBox in Controls.OfType<TextBox>())
{
textBox.TextChanged += onAnyTextChanged;
onAnyTextChanged(textBox, EventArgs.Empty); // Initialize
}
ActiveControl = Fortschrittsanzeige;
}
Multiple text boxes can all point to a common event handler.
System.Linq reduces the amount of code needed for things like matching and sorting.
What we're able to do is perform a validation based on all the textboxes whenever any textbox changes.
const int TEXTBOX_COUNT = 6;
private void onAnyTextChanged(object? sender, EventArgs e)
{
if(sender is TextBox textbox)
{
bool isValid;
if(textbox.PlaceholderText == "PLZ")
{
isValid = textbox.TextLength > 3;
}
else
{
isValid = !string.IsNullOrWhiteSpace(textbox.Text);
}
textbox.BackColor = isValid ? Color.White : Color.LightSalmon;
}
// Use System.Linq to count the number of valid textboxes (based on BackColor).
float countValid =
Controls
.OfType<TextBox>()
.Count(_=>_.BackColor== Color.White);
var pct = countValid / TEXTBOX_COUNT;
Fortschrittsanzeige.Value = (int)(pct * Fortschrittsanzeige.Maximum);
Sendebutton.Enabled = countValid.Equals(TEXTBOX_COUNT);
Fortschrittsanzeige.Visible = !Sendebutton.Enabled;
}
The handler allows for "special cases" and will make the Fortschrittsanzeige go backwards if the changed value is no longer valid.
When all textboxes are valid hide Fortschrittsanzeige and enable Sendebutton.
I have 3 columns in the ListView. From,Subject,Date
I'm using the OpenPop library.
private int numberofallmessages = 0;
private int countMsg = 0;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
OpenPop.Pop3.Pop3Client PopClient = new OpenPop.Pop3.Pop3Client();
PopClient.Connect("mail", 110, false);
PopClient.Authenticate("me", "me",
OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
List<string> uids = PopClient.GetMessageUids();
int messageCount = PopClient.GetMessageCount() -1;
numberofallmessages = messageCount;
allMessages = new List<OpenPop.Mime.Message>(messageCount);
for (int i = messageCount; i > 0; i--)//for (int i = messageCount - 1; i > -1; i--)
{
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return;
}
string currentUidOnServer = uids[i];
if (!seenUids.Contains(currentUidOnServer))
{
if (i > 0)
allMessages.Add(PopClient.GetMessage(i));
SaveFullMessage(PopClient.GetMessage(i), i);
w = new StreamWriter(emailsIDSFile, true);
w.WriteLine(currentUidOnServer);
w.Close();
int nProgress = (messageCount - i + 1) * 100 / messageCount;
backgroundWorker1.ReportProgress(nProgress, PopClient.GetMessageCount().ToString() + "/" + i);
}
}
PopClient.Disconnect();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbt.Value = e.ProgressPercentage;
pbt.Text = e.ProgressPercentage.ToString() + "%";
pbt.Invalidate();
label8.Text = e.UserState.ToString();
label8.Visible = true;
lvnf.Items.Add(new ListViewItem(new string[]
{
allMessages[countMsg].Headers.From.ToString(), //From Column
allMessages[countMsg].Headers.Subject, //Subject Column
allMessages[countMsg].Headers.DateSent.ToString() //Date Column
}));
countMsg += 1;
}
The problem is in the progresschanged event i think. Where i add the items to each column.
When it's adding the emails to the ListView i see it like this:
The problem is on the date column the date is fine but the time in not my time. Not sure of what place the time is but in my place it's now 1:52 AM
How can i get/set the time of my place ?
I couldn't find in the line:
allMessages[countMsg].Headers.DateSent.ToString()
How to change it to my time.
Try this:
allMessages[countMsg].Headers.DateSent.ToLocalTime().ToString();
You want to utilize the DateTime.ToLocalTime() method. It does the heavy lifting for you.
Hope this helps
Edit: Removed incorrect version as the documentation for OpenPop.Net states that the MessageHeader.DateSent property is in fact a DateTime object.
I'm trying to Search through a series of contacts. (saved in an xml file, and then recovered to the variable myContacts) the code for searching is fine, it gets the right results, my problem is Showing the contact in the text boxes.
This is my code for showing the results in the text boxes:
private void showContact(int index)
{
txtNameResult.Text = myContacts[index].getName();
txtFNameResult.Text = myContacts[index].getFName();
txtNumberResult1.Text = myContacts[index].getSingleNumber(0);
int position = 30;
for (int i = 1; i < myContacts[index].getNumCount(); i++)
{
TextBox formtxtBox = txtNumberResult1;
TextBox txtMyNum = new TextBox();
gbResult.Controls.Add(txtMyNum);
txtMyNum.Size = formtxtBox.Size;
txtMyNum.Location = new Point(formtxtBox.Location.X, formtxtBox.Location.Y + position);
position += 30;
txtMyNum.Text = myContacts[index].getSingleNumber(i);
txtMyNum.ReadOnly = true;
txtMyNum.Name = "txtNumberResult" + (i + 1).ToString();
txtMyNum.TabIndex = i + 2;
if (this.Height < 414)
{
gbResult.Height += 30;
this.Height += 30;
}
}//end of for
}//end of show contact
and this is my form:
![search
Form][1]
each contact can have up to 5 numbers and with each extra number a text box is added under the txtNumberResult1 and the groupbox and form height are extended.
the problem is that when I search for a contact with 5 numbers it shows it correctly but if I search for another contact AFTER that, the extra textboxes don't delete.
this is rather odd, but after an hour of debugging I finally found out that the problem is in my clearResults() code the gbResult.Controls.count (gbResult is the groupbox) is 8 (it should be 11 now)
this is my clearResults() code(the code that executes at the beginning of Save button click event, it resets everything):
private void clearResults()
{
gbResult.Focus();
txtNameResult.Text = "";
txtFNameResult.Text = "";
txtNumberResult1.Text = "";
foreach (Control txtBox in gbResult.Controls)
{
if (txtBox.GetType() == typeof(TextBox))
{
if (txtBox.Name != "txtNumberResult1" && txtBox.Name != "txtNameResult" && txtBox.Name != "txtFNameResult")
{
//remove the controls
txtBox.Text = "";
gbResult.Controls.Remove(txtBox);
txtBox.Dispose();
}//end of if
}//end of if
}//end of foreach
//shrink the form
while (this.Height > 294 && gbResult.Height > 129)
{
this.Height -= 30;
gbResult.Height -= 30;
}
}//end of clear results
thank you in advance and sorry if it seems a bit confusing!
PS: I can't post images as I don't have the required rep :|
EDIT:
This is the correct clearResults() method:
private void clearResults()
{
gbResult.Focus();
txtNameResult.Text = "";
txtFNameResult.Text = "";
txtNumberResult1.Text = "";
//foreach (Control txtBox in gbResult.Controls)
for (int i = 15; i > -1; i--)
{
try
{
var txtBox = gbResult.Controls[i];
if (txtBox.GetType() == typeof(TextBox))
{
if (txtBox.Name != "txtNumberResult1" && txtBox.Name != "txtNameResult" && txtBox.Name != "txtFNameResult")
{
//remove the controls
txtBox.Text = "";
gbResult.Controls.Remove(txtBox);
txtBox.Dispose();
}//end of if
}//end of if
}//end of try
catch (Exception)
{
continue;
}
}//end of for
//shrink the form
while (this.Height > 294 && gbResult.Height > 129)
{
this.Height -= 30;
gbResult.Height -= 30;
}
}//end of clear results
For those who have the same problem :)
In your clearResult() method try removing the controls in reverse order:
for (int i = 20; i > -1; i--)
I am creating a process scheduling calculator on C# and I created to listviews 1 for the inputs and one for the scheduling itself , however when I started coding the FCFS scheduling part I fail to convert the burst time subitem to double so I can add the waiting time here is some parts of the code and a screenshot to the form
public void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("Insert the required in the boxes");
}
else
{
ListViewItem Process = new ListViewItem(textBox1.Text);
Process.SubItems.Add(textBox2.Text);
Process.SubItems.Add(textBox3.Text);
Process.SubItems.Add(textBox4.Text);
listView1.Items.Add(Process);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
double temp = 0;
//First Come First Served
if (comboBox1.Text == "FCFS")
{
for (int i = 0; i < listView1.Items.Count; i++)
{
ListViewItem WaitingTime = new ListViewItem(listView1.Items[i].Text);
//temp = Convert.ToDouble(listView2.Items[i].SubItems[0]) + Convert.ToDouble(listView2.Items[i + 1].SubItems[0]);
if (listView2.Items.Contains(WaitingTime))
{
WaitingTime.SubItems.Add(temp.ToString());
listView2.Items.Add(WaitingTime);
}
else
{
WaitingTime.SubItems.Add(temp.ToString());
listView2.Items.Add(WaitingTime);
}
}
}
//SJF Non-preemptive
if (comboBox1.Text == "SJF non-preemptive")
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView2.Items.Add(listView1.Items[i].Text);
}
}
}
I tried several times and searched couple forms and all I get is FormatExpection.
Subitems[0] will hold the first subelement, which is the same as the Text of the item, also you cannot convert a ListViewItem.Subitem into a text, you need to use the Text property.
So you need to use:
listView2.Items[i].SubItems[1].Text
In your convert, also I recommend to use Double.TryParse instead of Convert.ToDouble, is faster and will tell you if it was parsed or not.
My program opens a series of forms all over the screen, am I able to code in an escape method, so on typing of the word "test" the program will close?
I was looking at the msdn keypress and how they use a switch, would I use something similar to check for the pressed key and if the correct key is pressed, a counter will increment of the correct key presses until, for "test", 4 will be reached, and if the pressed key is incorrect reset the counter and start over until the right order of keys are entered.
I hope that makes sense :P
public partial class TrollFrm : Form
{
int number = 1; //change to 2 and have the first instance of troll count = number - 1
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
public TrollFrm()
{
InitializeComponent();
this.Text = "Trololol - Troll Count: " + number;
startTimer();
}
private void TrollFrm_Load(object sender, EventArgs e)
{
//this.Enabled = false;
}
private void TrollFrm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
public void startTimer()
{
myTimer.Tick += new EventHandler(createForm);
//myTimer.Interval = 500;
myTimer.Start();
}
public void createForm(Object myObject, EventArgs myEventArgs)
{
Form frm = new TrollChildFrm();
Random randomX = new Random();
Random randomY = new Random();
frm.Text = "Trololol - Troll Count: " + number;
int xValue;
int yValue;
number++;
if (number % 2 == 0) //number is even.
{
xValue = (Convert.ToInt32(randomX.Next(1, 1920))) + 200;
yValue = (Convert.ToInt32(randomY.Next(1, 1080))) - 200;
}
else //number is not even.
{
xValue = (Convert.ToInt32(randomX.Next(1, 1920))) - 200;
yValue = (Convert.ToInt32(randomY.Next(1, 1080))) + 200;
}
frm.Show();
frm.Location = new Point(xValue, yValue);
if (number == 20)
{
myTimer.Stop();
}
}
It is an implementation you could use for scenario you described (not tested though):
int exitKeysCount = 0;
private void TrollFrm_KeyDown(object sender, KeyEventArgs e)
{
if (exitKeysCount == 0 && e.KeyCode == Keys.T)
exitKeysCount = 1;
else if (exitKeysCount == 1 && e.KeyCode == Keys.E)
exitKeysCount = 2;
else if (exitKeysCount == 2 && e.KeyCode == Keys.S)
exitKeysCount = 3;
else if (exitKeysCount == 3 && e.KeyCode == Keys.T)
this.Close();
else exitKeysCount = 0;
}
I assumed TrollFrm is your parent form, if they are all invoked somewhere else replace this.Close() with some function in main program function, also TrollFrm needs focus during key presses.
try this parent on your parent form.
int trollCount = 0;
private void TrollFrm_KeyDown(object sender, KeyEventHandler e)
{
if (trollCount == 0 && e.KeyCode == Keys.T)
{
trollCount = 1;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 1 && e.KeyCode== Keys.E)
{
trollCount = 2;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 2 && e.KeyCode== Keys.S)
{
trollCount = 3;
frm.Text = "Trololol - Troll Count:" + trollCount
}
else if (trollCount == 4 && e.KeyCode== Keys.T)
{
trollCount = 4;
this.Close();
}
else
trollCount = 0;
tell me if you need anything else.