increment how many times an image is displayed in a picturebox - c#

I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}

The reason is most likely that num is being instantiated to zero everytime the class is being instantiated

What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?

I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.

Related

System.ArgumentOutOfRangeException in a String

I tried to debug this and i cant figure out whats wrong with it.
Im trying to build a calculator but i keep getting this error.
double currentResult = 0;
int stringLengthStarter = 0;
int stringLengthCounter = 0;
public Form1()
{
InitializeComponent();
}
// Appends the numbers to the text box when the buttons are clicked
private void button1_Click(object sender, EventArgs e) // Click on the digit 1
{
if (clearingTextBoxFlag)
{
textBox1.Clear();
}
stringLengthCounter++;
textBox1.AppendText("1");
clearingTextBoxFlag = false;
}
private void plusButton_Click(object sender, EventArgs e) // Plus button clicked
{
pick = 1; // 1 - Plus operation
currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter));
stringLengthStarter = stringLengthCounter + 1;
stringLengthCounter = 0;
textBox1.AppendText("+");
}
private void equalsButton_MouseClick(object sender, MouseEventArgs e) // Mouse click on the equals button
{
textBox1.Clear();
if (pick == 1) // Plus operation
{
checkTextBox.Text = textBox1.Text;
currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); // The problem
textBox1.Text = "" + currentResult;
}
I'm trying to do 1+1= and it gets the execption at this line: currentResult = currentResult + Convert.ToInt32(textBox1.Text.Substring(stringLengthStarter, stringLengthCounter)); // The problem
In your equalsButton_MouseClick method, the first thing you do is to clear the textBox1, which will set the textBox1.Text to string.Empty. After that you try to make a substring of textBox1.Text, but the length of the string is 0, which is why your method is crashing. It's trying to access an index of the string that doesn't exist anymore.
Try moving the textBox1.Clear at the end of your method.

Pass a variable from inside an IF to the ELSE

I have a ASP.Net application that is a simple number generator. People guess, and it tells them whether or not they are correct. The issue I am having is in order to keep the randNum from changing each time the button is clicked to submit the answer (the page is reloaded), it is placed inside a Page.IsPostBack statement. The problem is the randomNum generated within this If is not accessible outside the If.
How can I get this variable accessable to other areas of my code while retaining the original randomNum? I want to use IsPostBack.
protected void btnGuess_Click(object sender, EventArgs e)
{
if (Page.IsPostBack == false) //the code only runs once when the form is loaded.
{
Random myGenerator = new Random();
myGenerator = new Random();
int randomNum = myGenerator.Next(1, 50);
}
else //code can always run
{
int guessedNum = Convert.ToInt32(txtGuess.Text);
if (guessedNum < randomNum)
{
MessageBox.Show("No. Low.");
txtGuess.Text = "";
}
else if (guessedNum > randomNum)
{
MessageBox.Show("No. High.");
txtGuess.Text = "";
}
else
{
MessageBox.Show("Yes");
txtGuess.Text = "";
}
}
}
Also, I have tried storing the variable as seen below:
HttpContext.Current.Session["RANDOM"] = randomNum;
and passing it to the else as:
int randomNum = Convert.ToInt32(HttpContext.Current.Session["RANDOM"]);
But doing this always results in a value of 0.
This is the only page that needs to use the variable. It does not need passed across pages, just functions.
Page.IsPostBack does not belong in a button click event. It needs to be added to Page_Load.
The way you have it now, it will always hit the else. i.e. it's always a postback in a button click.
protected void btnGuess_Click(object sender, EventArgs e)
{
int randomNum = Convert.ToInt32(HttpContext.Current.Session["RANDOM"]);
int guessedNum = Convert.ToInt32(txtGuess.Text);
if (guessedNum < randomNum)
{
MessageBox.Show("No. Low.");
txtGuess.Text = "";
}
else if (guessedNum > randomNum)
{
MessageBox.Show("No. High.");
txtGuess.Text = "";
}
else
{
MessageBox.Show("Yes");
txtGuess.Text = "";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) //the code only runs once when the form is loaded.
{
Random myGenerator = new Random();
myGenerator = new Random();
int randomNum = myGenerator.Next(1, 50);
HttpContext.Current.Session["RANDOM"] = randomNum;
}
}

how to insert values in a textbox C#

I don't know how to add a value in a textbox.
This is the code:
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
int score = 4;
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
int score = 1;
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
int score = 3;
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
int score = 2;
}
}
I want to insert the value of score in a textbox, so it will show me the score of each item i've selected from combobox.
I tried with this:
private void scoringTextBox_TextChanged(object sender, EventArgs e)
{
scoringTextBox.Text = score.toString();
}
But it doesn't recognize it. The error is: The name 'score' does not exist in this context. How can I make this work ?
Thank you.
You must declare variable score outside of ComboBox SelectedIndexChanged handler. You're declaring it in the handler and it's being used only in the method, not in the whole class (not in the whole form in your case).
public class Form1
{
int score = 0;
//somewhere in the code
score = 1; //there is no need to specify 'int' here - you will create an local variable with the same name then
}
I recommend you to learn through tutorials, because the question is rather simple.
Though #psNytrancez answer is the simplest for you, you will not get far in C# without understanding how variables work.
The problem is with the lines that look like this:
else if (starecivilaComboBox.SelectedIndex == 1)
{
int score = 4;
}
it means that you create a variable "score", but that the variable will only exists between the two braces "{" and "}". In order to actually keep a value, you need to expand its scope (instruction video). if you edit all those lines to just read
else if (starecivilaComboBox.SelectedIndex == 1)
{
score = 4;
}
and instead put it outside the method declaration like this
int score =0;
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//the rest of the method.
then you should be fine.
It is because you are declaring your score inside of the starecivilaComboBox_SelectedIndexChanged method so it is local to that method and cannot be accessed outside of it.
As stated above, you must declare score outside of your private method but inside your class. Code should look similar to this:
private int score = 0;
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
score = 4;
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
score = 1;
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
score = 3;
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
score = 2;
}
}
private void scoringTextBox_TextChanged(object sender, EventArgs e)
{
scoringTextBox.Text = score.toString();
}
private void starecivilaComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (starecivilaComboBox.SelectedIndex == 0)
{
MessageBox.Show("This selection is not valid!");
}
else if (starecivilaComboBox.SelectedIndex == 1)
{
scoringTextBox.Text = "4";
}
else if (starecivilaComboBox.SelectedIndex == 2)
{
scoringTextBox.Text = "1";
}
else if (starecivilaComboBox.SelectedIndex == 3)
{
scoringTextBox.Text = "3";
}
else if (starecivilaComboBox.SelectedIndex == 4)
{
scoringTextBox.Text = "2";
}
}
Do it after this
else if (starecivilaComboBox.SelectedIndex == 4)
{
int score = 2;
}
Add this
scoringTextBox.Text = score.toString();
The scope for variable / object score is the problem
you are trying to access a variable that has limited scope (function level only)
simply create a private variable score so it can be accessed through the class.

c# programmable selecting dropdown value

I am new at C# and it seems the following code below does not seem to select my combobox value:
private void button1_Click(object sender, EventArgs e)
{
cbPortNumber.SelectedValue = 3;
or
cbPortNumber.setValue("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.FindString("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.Items.IndexOf(cbPortNumber.Items.FindByValue("HDMI 4"));
}
The dropdown looks like this:
All code above does not seem to select HDMI 4 on the list... I dont have any errors but i also don't have it being selected.
Any help would be great!
update showing combobox
UPDATE 2
//
// cbPortNumber
//
this.cbPortNumber.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.cbPortNumber.Enabled = false;
this.cbPortNumber.FormattingEnabled = true;
this.cbPortNumber.Location = new System.Drawing.Point(174, 40);
this.cbPortNumber.Name = "cbPortNumber";
this.cbPortNumber.Size = new System.Drawing.Size(133, 21);
this.cbPortNumber.TabIndex = 11;
this.cbPortNumber.Text = "global_hdmi_port";
this.helpPortNumber.SetToolTip(this.cbPortNumber, "The HDMI port number, to which you connected your USB-CEC adapter.");
this.cbPortNumber.SelectedIndexChanged += new System.EventHandler(this.cbPortNumber_SelectedIndexChanged);
#region Global settings
public CECSettingByte HDMIPort
{
get
{
if (!_settings.ContainsKey(KeyHDMIPort))
{
CECSettingByte setting = new CECSettingByte(KeyHDMIPort, "HDMI port", 1, _changedHandler) { LowerLimit = 1, UpperLimit = 15, EnableSetting = EnableHDMIPortSetting };
setting.Format += delegate(object sender, ListControlConvertEventArgs args)
{
ushort tmp;
if (ushort.TryParse((string)args.Value, out tmp))
args.Value = "HDMI " + args.Value;
};
Load(setting);
_settings[KeyHDMIPort] = setting;
}
return _settings[KeyHDMIPort].AsSettingByte;
}
}
Update 3
And this is what fires the action after selecting something in that dropdown:
private void OnSettingChanged(CECSetting setting, object oldValue, object newValue)
{
if (setting.KeyName == CECSettings.KeyHDMIPort)
{
CECSettingByte byteSetting = setting as CECSettingByte;
if (byteSetting != null)
{
if (!Settings.OverridePhysicalAddress.Value)
Config.HDMIPort = byteSetting.Value;
CECActions.SetConnectedDevice(Settings.ConnectedDevice.Value, byteSetting.Value);
}
}
So this code is working fine for me:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 2;
}
you can not access a ItemSource if there are no items to access. The simple way is to Init the items over the Desinger
( Sory for the nonlocalized IDE ) than you can set the Property SelectedIndex to a Index that exits. The other way is to Add all HDMI items with the Combobox1.Items.Add function.
If you ever used Forms in VB ... its still the same
public Form1()
{
InitializeComponent();
var hdmi = "HDMI";
for (int i = 1; i < 15; i++)
{
comboBox1.Items.Add( hdmi + i);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count >= 2)
comboBox1.SelectedIndex = 2;
}

Select a particular line in textbox?

I have a two forms, 1 and 2. Form1 has one textbox and form2 has a textbox and button. I want to go to a specified line, meaning that when I enter the value of form2's textbox then my mouse cursor goes to form1's textbox.
private void button1_Click(object sender, EventArgs e)
{
int line = Form1.ab;
for (int i = 1; i < line; i++)
{
if (i == Convert.ToInt16( textBox1.Text))
{
// fr.textbox1 is a textbox form1 and
// textbox1.text is a textbox of the form1
fr.textBox1.SelectionStart =
int.Parse( textBox1.Text) ;
fr.textBox1.ScrollToCaret();
break;
}
}
}
The TextBox.GetFirstCharIndexFromLine method finds the index of the first character of a line.
So your selection starts there. Then find the end of that line, which is Environment.NewLine or the end of the text.
Since the line number is entered by the user you should use int.TryParse to handle invalid input.
private void button1_Click(object sender, EventArgs e)
{
int lineNumber;
if (!int.TryParse(textBox2.Text, out lineNumber) || lineNumber < 0)
{
textBox1.Select(0, 0);
return;
}
int position = textBox1.GetFirstCharIndexFromLine(lineNumber);
if (position < 0)
{
// lineNumber is too big
textBox1.Select(textBox1.Text.Length, 0);
}
else
{
int lineEnd = textBox1.Text.IndexOf(Environment.NewLine, position);
if (lineEnd < 0)
{
lineEnd = textBox1.Text.Length;
}
textBox1.Select(position, lineEnd - position);
}
}
Apply this logic to your code, and recode it as you need.
private void button1_Click(object sender, EventArgs e)
{
if (textBox_Form1.Text.Contains(textBox_Form2.Text))
{
textBox_Form1.Focus();
textBox_Form1.SelectionStart = textBox_Form1.Text.IndexOf(textBox_Form2.Text);
textBox_Form1.SelectionLength = textBox_Form2.Text.Length;
}
}
try something like;
int lineNumber = Form1.ab;
// split the contents of the text box
string text = textBox1.Text;
string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
if (lineNumber < 0 || lineNumber > lines.Length)
{
MessageBox.Show("The line number is does not exist");
return;
}
// get the character pos
int selStart = 0;
for (int i = 0; i < (lineNumber - 1); i++)
{
selStart += lines[i].Length + Environment.NewLine.Length;
}
textBox1.Focus();
textBox1.SelectionStart = selStart;
textBox1.SelectionLength = lines[lineNumber - 1].Length;
Note: you can access the other text box directly in the other form by going to the Form2 designer, clicking the text box and going to Properties. In the Properties dialog, look for a property called Modifiers and change the value to internal or public. This will allow you to access the text box value in the other form directly like so;
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2Instance = new Form2();
string sampleText = form2Instance.textBox1.Text;
}
If you need to know further samples on how to access controls/details on other forms, let me know.
You are creating a NEW form1 where the textbox is likely to be blank, and calling GetPass() on that empty form. You need an instance of the already-opened form1 where the textbox might have a value. for more information
click here
Try the below code
var sdr = (System.Windows.Controls.TextBox) sender;
if (!string.IsNullOrEmpty(sdr.Text)) {
var start = sdr.Text.LastIndexOf(Environment.NewLine, sdr.CaretIndex);
var lineIdx = sdr.GetLineIndexFromCharacterIndex(sdr.CaretIndex);
var lineLength = sdr.GetLineLength(lineIdx);
sdr.SelectionStart = start + 1;
sdr.SelectionLength = lineLength;
sdr.SelectedText.Substring(0, sdr.SelectedText.IndexOf(Environment.NewLine) + 1);
Clipboard.SetText(sdr.SelectedText);
}
maybe this better:
{
...
string SelectedText = fr.textBox1.Lines[line];
int SelectedTextPos = fr.textBox1.Text.IndexOf(SelectedText);
int SelectedTextLen = SelectedText.Lenght;
fr.textBox1.Select(SelectedTextPos, SelectedTextLen);
fr.textBox1.ScrollToCaret();
...
}

Categories