I'm wanting to add +1 every time a radiobox or checkbox is used. This happens when calculate is pressed and putting it into a string then when the summary button is pushed it displays it in a messagebox with the final total of times it was pushed.
this is my code so far but it doesnt seem to work,
This is my Calculate button
int Quantity;
int Finalprice;
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Early Evening Meal
if (earlyEveningRadioButton.Checked == true)
{
Meal = Early;
}
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
//Late evening options
if (lateEveningRadioButton.Checked == true)
{
Meal = Late;
}
//Late Evening, Corner table and Dedicated waiter selected.
else if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Table + Waiter;
}
//Late Evening and Dedicated waiter selected.
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
//Late Evening and Corner Table
else if (tableCheckBox.Checked)
{
Extras = Table;
;
}
try
{
Quantity = int.Parse(guestTextBox.Text);
Mealprice = (Meal * Quantity);
Finalprice = (Mealprice + Extras);
finalAmountLabel.Text = Finalprice.ToString("C");
}
catch
{
guestTextBox.Focus();
guestTextBox.SelectAll();
MessageBox.Show("Please enter a quantity in numerical form","Quantity Error!");
}
This is the Summary Button
int TotalLunch = 0;
int TotalEarly = 0;
int TotalLate = 0;
int TotalBookings = 0;
int TotalWaiters = 0;
int LateWaiters = 0;
int EarlyWaiters = 0;
int LunchWaiters = 0;
int TotalCornerTables = 0;
int EarlyCornerTables = 0;
int LateCornerTables = 0;
int LunchCornerTables = 0;
if (earlyEveningRadioButton.Checked == true)
{
TotalEarly = +1;
TotalEarly.ToString();
}
else if (earlyEveningRadioButton.Checked && waiterCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyWaiters.ToString();
}
else if (tableCheckBox.Checked && earlyEveningRadioButton.Checked)
{
EarlyCornerTables = +1;
EarlyCornerTables.ToString();
}
else if (waiterCheckBox.Checked && tableCheckBox.Checked)
{
EarlyWaiters = +1;
EarlyCornerTables = +1;
EarlyWaiters.ToString();
EarlyCornerTables.ToString();
}
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
Any suggestions or help would be greately appriciated :)
The best way you can do this, is using the eventhandler CheckedChanged foreach checkbox.
in the event do this:
if(checkBox.Checked)
{
//int +1
}
I'll start with an answer to your question...
Your code will not increment TotalEarly by one, but it will assign +1 to the variable.
TotalEarly = +1;
For incrementing you should either use the ++ or the += operator:
TotalEarly++; // increments by 1
TotalEarly += 1; // also increments by 1, but += can be used with other numbers
Some other notes, not related to your question:
TotalEarly.ToString();
This will not do anything since you do not assign the result to a variable. This will not convert TotalEarly to a string variable! The type of TotalEarly is fixed to int as you specified.
You would have to write
var totalEarlyString = TotalEarly.ToString();
to be able to use the result afterwards. You might wonder why your MessageBox still displays that number as a string although you use the int variable:
"Number of Early Bookings" + " " + TotalEarly
This is because the ToString() method is called automatically in this case. So, you can really save some lines by removing your calls to ToString() after the assignments.
One more thing: local variables are typically named using camelCase. That means, the first character is lower case and every additional word starts with an uppercase character. PascalCase (i.e. also starting with uppercase character) is typically used for properties, methods, class names etc, but not for local or member variables.
It seems like you want each value in the MessageBox to be on a separate line (at least I assume that is why you added some spaces at the end of the first line:
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + " " +
"Number of Early Evening Waiters" + " " + EarlyWaiters
+ "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
);
This might not work on all machines. The MessageBox has different sizing behavior on differnt versions of Windows. Some will wrap the text to multiple lines, some will not, or at least at different widths!
Therefore, you better add an Environment.NewLine at the end of each line. This will add a line break to your string which will be interpreted as such by the MessageBox:
MessageBox.Show("Number of Early Bookings " + TotalEarly + Environment.NewLine +
"Number of Early Evening Waiters " + EarlyWaiters + Environment.NewLine +
"Number of Early Evening Corner Tables tables " + EarlyCornerTables);
Accordion to your comments in your code I think the problem is that your if else statements are wrong.
Q1: Should it calculate on every checkbox click or only when you click calculate?
- if it should calculate on every checkbox click then you have to use the CheckedChanged event as RaZor points out.
Q2: Is it true that de client can have a lunch + waiter + table?
- if that is true then your if else statement should be as follows:
if (lunchRadioButton.Checked == true)
{
Meal = Lunch;
if (tableCheckBox.Checked && waiterCheckBox.Checked)
{
Extras = Waiter + Table;
}
else if (waiterCheckBox.Checked)
{
Extras = Waiter;
}
else if (tableCheckBox.Checked)
{
Extras = Table;
}
}
Related
I have a Form with 6 arrays, 15 elements each. I wrote them in a way that if I search for myself (being the 1st element in the string[] name array), the form would load the 1st element of every array: age, gender, hobby, photo etc.
Here is the part of the pictureBox code I'm using
//I have more arrays here, like: Name,Gender,Age,Hobby,Place & Talent
string[] photo=new string[] { "764.jpg", " 765.jpg", " 766.jpg", " 767.jpg"," 765.jpg", " 767.jpg", " 768.jpg", " 769.jpg", " 770.jpg", " 771.jpg", " 772.jpg", " 773.jpg", " 774.jpg", " 775.jpg", " 776.jpg"};
string name="",gender="",place="",warning=""; int age = 0; string image="";
for (int i = 0; i < 15; i++)
{
if (textBox6.Text == emri[i])
{
//I applied every element of every array to the declared variables
image = photo[i];
j++;
}
if (j == 1)
{
//Associated the textBoxes with the variables
pictureBox1.Image = Image.FromFile(#"C:\Users\NComputers\Documents\Visual Studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\Sony Xperia\" + image);
}
else
{
MessageBox.Show("Person not found!");
}
While there are no errors shown, the picture simply doesn't load. All the other items are working. Help?
ok what im trying to do here is the following
private void addgsc()
{
if (File.Exists(hud))
{
{
string s = " itemDef\n\r"
+ "{"
+ " name \"zombiecounter\"\n\r"
+ " rect 100 70 0 0 HORIZONTAL_ALIGN_CENTER VERTICAL_ALIGN_BOTTOM\n\r "
+ " textscale .5\n\r"
+ " textstyle ITEM_TEXTSTYLE_SHADOWED\n\r"
+ " textfont UI_FONT_OBJECTIVE\n\r"
+ " textalign ITEM_ALIGN_CENTER\n\r"
+ " forecolor 1 0 0 1\n\r"
+ " exp text (\"Zombies Left: \" + dvarInt(\"zombie_counter\"))\n\r"
+ " visible when (dvarInt(\"zombie_counter\") > 0);\n\r"
+ "decoration\n\r"
+ "} ";
string file = hud;
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("playerscores"));
if (index != -1)
{
lines.Insert(index + 1, s);//""
}
System.IO.File.WriteAllLines(file, lines);
MessageBox.Show("done");
}
}
and im looking for a line in a code like this
itemDef
{
name "playerscores"
rect 0 0 100 0
ownerdraw CG_COMPETITIVE_MODE_SCORES
visible 1
}
but what i want to do is find player scores then find the last } at the end and add it there because currently its adding it right under player scores but im not sure how i can get it to go to find that and then find the closest } one of those and add it under neath that so its in a new block not added into the player score one so would want something like the following
image 1
I'm a bit unclear of the desired output, so the below code may be more than what you need but should get you on the right track. Please forgive syntax errors.
EDIT: I reread the question a few times, and think this is what you are looking for.
var allLinesInFile = System.IO.File.ReadAllLines(file);
var isPlayerScore = false;
var linesToWrite = new List<string>();
var linesToAdd = new List<string> {
"itemDef\n\r",
"{",
" name \"zombiecounter\"\n\r",
//and so on
"}"
};
foreach (var line in allLinesInFile)
{
linesToWrite.Add(line);
if (line.IndexOf("playerscores", StringComparison.OrdinalIgnoreCase) >= 0)
{
//starting of data detected.
isPlayerScore = true;
}
else if (isPlayerScore == true && line.IndexOf("}") >= 0)
{
//end of data detected
isPlayerScore = false;
linesToWrite.AddRange(linesToAdd);
}
}
System.IO.File.WriteAllLines(file, linesToWrite);
MessageBox.Show("done");
I tried to debug this code, but I cannt how to fix it.
If I use this code, my WF run:
try
{
rtxttdwhat.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString();
lbtdtime1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString() +
":" + dataGridView1.CurrentRow.Cells[0].Value.ToString();
the other, it's show INDEX OUT OF RANGE:
int a, b;
a = 1;
b = a+1;
try
{
if (int.Parse(dataGridView1.Rows[a].Cells[1].Value.ToString()) == int.Parse(lbhour.Text) &&
int.Parse(dataGridView1.Rows[a].Cells[0].Value.ToString()) == int.Parse(lbmin.Text))
{
a = a + 1;
b = a + 1;
}
rtxttdwhat.Text = dataGridView1.Rows[a].Cells[8].Value.ToString();
lbtdtime1.Text = dataGridView1.Rows[a].Cells[1].Value.ToString() +
":" + dataGridView1.Rows[a].Cells[0].Value.ToString();
I am not 100% sure what are you doing, especially with b? But you could try this:
int RowCount = dataGridView1.Rows.Count;
if(a <= RowCount)
{
//Youre Code
}
else
{
//Out of Range
}
Hi This link may be useful for you
IndexOutOfRangeException
Modify your code and Check for Rows and Cells Counts first before accessing them.
I'm trying to add numbered list functionality to a text editor. RichTextbox already provides the SelectionBullet property to change a selection to a bulleted list. But i was unable to find a similar property to generate numbered list. Is there any standard way to create a numbered list on Richtextbox. If not, i would have to implement it myself so code snips that could help me do that will help, Thank you.
I know that a link is not gernerally accepted as a good answer, however the article RichTextBox with Search Line Numbering, Bulleting, Printing, Searching Support on CodeProject could probably help you out quite a bit with what you are looking for.
In this article, the author extends the RichTextBox control into something that can do what you are asking (and more), plus the code is posted there for all to see.
Well, i implemented it as follows.
private void btnNumbers_Click(object sender, EventArgs e)
{
string temptext = rtbMain.SelectedText;
int SelectionStart = rtbMain.SelectionStart;
int SelectionLength = rtbMain.SelectionLength;
rtbMain.SelectionStart = rtbMain.GetFirstCharIndexOfCurrentLine();
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = "1. ";
int j = 2;
for( int i = SelectionStart; i < SelectionStart + SelectionLength; i++)
if (rtbMain.Text[i] == '\n')
{
rtbMain.SelectionStart = i + 1;
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = j.ToString() + ". ";
j++;
SelectionLength += 3;
}
}
private void rtbMain_KeyDown(object sender, KeyEventArgs e)
{//this piece of code automatically increments the bulleted list when user //presses Enter key
int tempNum;
if (e.KeyCode == Keys.Enter)
try
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()]))
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.')
tempNum = int.Parse(rtbMain.Text.Substring(rtbMain.GetFirstCharIndexOfCurrentLine(),2));
else tempNum = int.Parse(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()].ToString());
if (rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1] == '.' || (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.'))
{
tempNum++;
rtbMain.SelectedText = "\r\n" + tempNum.ToString() + ". ";
e.SuppressKeyPress = true;
}
}
}
catch{}
}
Here is my answer... which is easily readable and refineable. I took a much different approach but added the ability to remove the numbered list within the selection if it already exists. Please note that so far I have only lightly tested it and it seems to work good... but it may need further refinement.
private void btnOrdered_Click(object sender, EventArgs e)
{
string[] splitSelection = null;
// If selection split selection else split everything
if (this.txtCaptionEditor.SelectionLength > 0)
{
splitSelection = this.txtCaptionEditor.SelectedText.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
else
{
splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
bool Exists = false;
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
// If Ordered List Allready exists in selection then remove else add
if (!string.IsNullOrEmpty(splitSelection[i]))
{
if (splitSelection[i].Substring(0, 2) == "1.") { Exists = true; }
}
}
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
int lineCount = (i + 1);
if (Exists)
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(Convert.ToString(lineCount) + ". ", "");
}
else
{
if(!string.IsNullOrEmpty(splitSelection[i]))
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(splitSelection[i], Convert.ToString(lineCount) + ". " + splitSelection[i]);
}
}
}
}
private void txtCaptionEditor_KeyDown(object sender, KeyEventArgs e)
{
string[] splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
if (e.KeyCode == Keys.Enter)
{
// Get Current Line Position
int currentLine = this.txtCaptionEditor.GetLineFromCharIndex(this.txtCaptionEditor.SelectionStart);
// Only Run if the previous line is greater than zero
if ((currentLine) >= 0)
{
// Loop through 100 possible numbers for match you can go higher
// If you think your numbered list could go above 100
for (int i = 0; i < 100; i++)
{
if (splitSelection[(currentLine)].Substring(0, 2) == Convert.ToString((i + 1)) + ".")
{
// If the substring of the current line equals a numbered list value.. enumerate next line
this.txtCaptionEditor.SelectedText = "\n" + (i + 2) + ". ";
e.SuppressKeyPress = true;
}
}
}
}
}
This application works as if you were playing the lottery, you pick 5 numbers from a comboBox, click a button to generate the 5 key numbers and then you press another button to check the results (after you introduce the prize monei on the textbox below, AKA "prémio").
The button that does the checking is the highlighted one Verificar Prémio.
Here's it's code:
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox1.Text!="Prémio em €")
{
int contador = 0;
for (int i = 1; i <= 5; i++)
{
string posicao = i.ToString();
for (int c = 1; c <= 5; c++)
{
string poschave = c.ToString();
if (listBox1.Items.IndexOf(posicao) ==
listBox2.Items.IndexOf(poschave))
{
contador = contador + 1;
}
}
i = int.Parse(posicao);
double valor;
double premio = double.Parse(textBox1.Text);
if (contador == 5)
{
MessageBox.Show(" Parabens ganhou o 1º premio acertou 5 números
o seu prémio é de " + premio + "€");
}
else
{
if (contador == 4)
{
valor = premio * 0.75;
MessageBox.Show(" Acertou 4 numeros o seu premio é: " +
valor + "€");
}
else
{
if (contador == 3)
{
valor = premio * 0.5;
MessageBox.Show("Acertou 3 numeros o seu premio é: " +
valor + "€");
}
else
if (contador <= 2)
{
MessageBox.Show(" Infelizmente nao ganhou,
nada tente outra vez");
}
}
}
}
}
}
Whatever I do, it always shows the messageBox saying I got all 5 correct...
EDIT:
listBox1 is the one on the left, (3, 9, 17, 20, 10), you choose them from the combobox and when you Click "Apostar" it is added to it.
listBox2 is the box on the right.
EDIT2:
By replacing
for (int c = 1; c <= 5; c++)
{
string poschave = c.ToString();
if (listBox1.Items.IndexOf(posicao) == listBox2.Items.IndexOf(poschave))
{
contador = contador + 1;
}
}
with
foreach (var item in listBox1.Items)
{
// Convert it to string to avoid object reference comparison. Not 100%
// sure if this is needed
string value = item.ToString();
if (listBox2.Items.Contains(value))
contador++;
}
The error doesnt show anymore however it still isnt working properly, my guess is that the program is checking if they match, then get the result, therefore it always show "you won nothing" 5 times in a row...
How can I fix this?
I don't understand Spanish(?) so it's very hard to understand your code (please use english variable names, even if you have a localized UI)
However, one cause of the problem could be this line:
listBox1.Items.IndexOf(posicao) == listBox2.Items.IndexOf(poschave)
In case neither posicao or poschave is found in their respective listboxes, -1 will be returned and the expression will be true (i.e. contador will be incremented). I'm guessing this is not the desired behavior.
If you instead want to check if an item in the left listbox is also available in the right, then you could do:
void Button_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "Prémio em €")
return;
int numMatches = 0;
foreach (var item in listBox1.Items)
{
if (listBox2.Items.Contains(item))
numMatches++;
}
// numMatches will now contain the number of elements in the left
// listbox that also exist in the right listbox
if (numMatches > 2)
{
double premio = Double.Parse(textBox1.Text);
double prize = 0;
if (numMatches == 5)
prize = premio * 1.0;
if (numMatches == 4)
prize = premio * 0.75;
else
prize = premio * 0.5;
// Use string.Format() instead to get fancier formatting of numbers
Messagebox.Show ("Sweet, you got " + numMatches + " out of 5 correct numbers. Your prize is " + prize + "€");
}
else
{
MessageBox.Show("Sorry, not enough matches - you win nothing!");
}
}
EDIT:
The reason you get 5 message boxes is because you have the call to Messagebox.Show() inside a for loop that loops five times. I've updated the code sample above to do what I think you want your button callback to do
Your source is way too complicated, you have two loops, one integer > string followed by string > integer... try this:
int count = 0;
for (int i = 0; i < 5; i++)
{
if (listBox2.Items.IndexOf(listBox1.Items[i]) > 0)
{
count++;
}
}
// count is 0 - 5
You only check for 5 numbers of the left ListBox if it is in the right ListBox.