How to do looping in C# programming? - c#

I have to allow 20 balls to move around the screen. I would like to know how do I use a loop so I would not have to type the codes out long. Currently, the codes I have are
for (int i = 0; i < ballSpeedXAxis.Length; i++)
{
ballSpeedXAxis[i] = 1;
}
for (int i = 0; i < ballSpeedYAxis.Length; i++)
{
ballSpeedYAxis[i] = 1;
}
private void OnUpdate(object sender, object e)
{
Canvas.SetLeft(this.ball1, this.ballSpeedXAxis[1] + Canvas.GetLeft(this.ball1));
Canvas.SetTop(this.ball1, this.ballSpeedYAxis[1] + Canvas.GetTop(this.ball1));
Canvas.SetLeft(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetLeft(this.ball2));
Canvas.SetTop(this.ball2, this.ballSpeedXAxis[2] + Canvas.GetTop(this.ball2));
...
Canvas.SetLeft(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetLeft(this.ball20));
Canvas.SetTop(this.ball20, this.ballSpeedXAxis[20] + Canvas.GetTop(this.ball20));
}
ball1, ball2 ... ball3 are images name.

There are varying ways.. the most obvious being instead of this:
Image ball1;
Image ball2;
Image ball3;
// .. etc ...
You would put those in an array also:
Image[] balls = new Image[20];
..same with your speeds. Then you can change your update method to this:
private void OnUpdate(object sender, object e) {
for (int i = 0; i < balls.Length; i++) {
Canvas.SetLeft(balls[i], ballSpeedXAxis[i] + Canvas.GetLeft(balls[i]));
Canvas.SetTop(balls[i], ballSpeedYAxis[i] + Canvas.GetTop(balls[i]));
}
}
Others include putting the already created images into a List<Image>.. but that's a bit yuck.

Related

Replace multiples words in text document C#

So I'm trying to get a program running to save me copying and pasting loads of text for android studio. For this I have created listboxes with all the different bits of information required, added button click event to create a document, and another button click event to add the text into the document. So far I'm able to generate all the text when adding one set of latlongs, but I can't seem to work out how to add another set latlongs in..
For example
I need:
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.79940000000, 31.01680000000)).title(bbb));
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.80150000000,
31.03650000000)).title(ccc));
But all's I am getting is:
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.79940000000, 31.01680000000)).title(bbb));
googleMap.addMarker(new MarkerOptions().position(new LatLng(-17.80150000000, 31.01680000000)).title(bbb));
The Longitude value is not changing? I'm hoping all of this makes sense?
string path = Environment.CurrentDirectory + "/" + "latlong.txt";
private void button1_Click(object sender, EventArgs e)
{
if (!File.Exists(path))
{
File.CreateText(path);
MessageBox.Show("File has been created.");
}
}
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter stwr = new StreamWriter(path))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + ")).title(" + "bbb" + "));");
}
stwr.Close();
string text = File.ReadAllText("latlong.txt");
for (int ii = 0; ii < listBox2.Items.Count; ii++)
{
text = text.Replace("ii", Convert.ToString(listBox2.Items[ii]));
}
File.WriteAllText("latlong.txt", text);
}
}
I guess the problem is that Replace is replacing all occurences of ii, so if you debug your loop you'll see that only the first time iiis replaced by the first item in your listBox2. To solve that,i think you should add the index to ii,something like this
private void button2_Click(object sender, EventArgs e)
{
using (StreamWriter stwr = new StreamWriter(path))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + i + ")).title(" + "bbb" + "));");
}
stwr.Close();
string text = File.ReadAllText("latlong.txt");
for (int ii = 0; ii < listBox2.Items.Count; ii++)
{
text = text.Replace("ii"+ii, Convert.ToString(listBox2.Items[ii]));
}
File.WriteAllText("latlong.txt", text);
}
}
Notice that in the first loop i'm adding "ii" + i and in the second i'm replacing "ii"+ii

Insert data in RichTextBox C#

My code:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text = infos;
}
timer4.Stop();
}
I want to insert all of 10 src values in RichTextBox, while my code do it only once.
You can use AppendText
Replace
richTextBox1.Text = infos;
with
richTextBox1.AppendText(infos);
OR
richTextBox1.Text += infos + Environment.NewLine;
This line is wrong.
richTextBox1.Text = infos;
This is right.
richTextBox1.AppendText= infos;
What your code is doing is setting the text to equal each infos, 10 times over.
So I'm guessing your output would be the last infos variable? What you might want to do instead is this:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text += infos; // the "+=" will add each infos to the textbox
}
timer4.Stop();
}
As you can see, if you use the += instead of just =, it will add each iteration to the whole, instead of just overriding the whole value each time.

Copy paste from a text box adds extra lines

So basically I have a button that takes the strings delimited by line breaks in one text box that then formats them a particular way and puts them in a different text box. Everything looks fine when I run the code, however, when I copy and paste the text from the second textbox to a different place, it adds a line break after everything that I took from the original box.
private void ToTableButton_Click(object sender, EventArgs e)
{
StringBuilder tableText = new StringBuilder();
string[] lines = BasicTextBox.Text.Split('\n');
TableTextBox.Clear();
try
{
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append(lines[i]);
}
else
{
tableText.Append(lines[i] + " | ");
}
}
tableText.Append(Environment.NewLine);
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append("--");
}
else
{
tableText.Append("--|");
}
}
int currentPos = Convert.ToInt32(columnsUpDown.Value);
while (currentPos <= lines.Length)
{
tableText.Append(Environment.NewLine);
for (int i = 0; i < columnsUpDown.Value; i++)
{
if (i == columnsUpDown.Value - 1)
{
tableText.Append(lines[currentPos]);
}
else
{
tableText.Append(lines[currentPos] + " | ");
}
currentPos++;
}
}
}
catch
{
}
TableTextBox.Text = tableText.ToString();
}
I thought maybe this be because the split doesn't remove the \n but I wasn't sure how to remove it afterwards. Any advice would be greatly appreciated.
I would think that trimming the lines[currentPos] would be the correct way...
tableText.Append(lines[currentPos].ToString().Trim());

C# Index was outside the bounds of the array - specific help, please

I'm working on a small programme for booking seats on an airplane - And I keep getting this error. i want the programme to show me which seats on the plane (flysaeder) are being booking by what passenger (passagerer). Only, If I enter in more seats than I have passengers, it won't run - I need it to allow open seats (less "passagerer" than "flysaeder"). What am I doing wrong?
I'm kinda new at this, so I apologize for poor explanation.
Error occurs on "listeOverPassagerer[index] = listeOverPassagerer[i];".
namespace eksamenvingerne
{
public partial class Form1 : Form
{
int flysaeder;
int passagerer;
Random tilfældighed = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
{
int.TryParse(txtsaeder.Text, out flysaeder);
int.TryParse(txtantalpassagere.Text, out passagerer);
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
else
{
int[] listeOverPassagerer = Enumerable.Range(0, passagerer).ToArray();
int[] flypladser = new int[flysaeder];
for (int i = 0; i < flysaeder; i++)
{
int index = tilfældighed.Next(0, passagerer);
flypladser[i] = tilfældighed.Next(i, passagerer);
flypladser[i] = listeOverPassagerer[index];
listeOverPassagerer[index] = listeOverPassagerer[i];
}
for (int i = 0; i < flypladser.Length; i++)
{
listBox1.Items.Add("Sæde #" + i + ": Passagernr.:" + flypladser[i]); //listboxen udskriver indholdet af hver eneste plads.
}
}
}
}
}
}
Your logic actually is causing this problem:
First you make sure that passagerer <= flysaeder
if (passagerer > flysaeder)
{
MessageBox.Show("Ingen frie pladser!");
}
Then you do a for loop from 0 to flysaeder -1
for (int i = 0; i < flysaeder; i++)
But flysaeder might be larger than passagerer hence your access of listeOverPassagerer[i] will throw an exception since listeOverPassagerer is of length passagerer

C# Need help editing my line numbering code

I got a code for line numbering, it works perfectly fine for numbering lines the regular way but I'm looking for something a little bit different. I want my code to only count line breaks when i press enter(the program receives an return keycode) and not then the textbox automatically cut the lines with word wrapping. This is the code i'm using right now:
//Instructions
int maxLC = 1; //maxLineCount - should be public
private void InstructionsSyncTextBox_KeyUp(object sender, KeyEventArgs e)
{
int linecount = InstructionsSyncTextBox.GetLineFromCharIndex(InstructionsSyncTextBox.TextLength) + 1;
if (linecount != maxLC)
{
InstructionsLineNumberSyncTextBox.Clear();
for (int i = 1; i < linecount + 1; i++)
{
InstructionsLineNumberSyncTextBox.AppendText(Convert.ToString(i) + "\n");
}
maxLC = linecount;
}
}
How i think i would be done easiest is by saving the line count every time someone presses enter to a list and also everytime someone presses enter it updates the line number texbox with every line number at positions said in list. But i have no idea how to detect when an return is removed. Anybody knows how to solve this?
Extremely basic example that counts the lines in your code you posted:
class Program
{
static void Main(string[] args)
{
string stringFromTextBox =
#" int maxLC = 1; //maxLineCount - should be public
private void InstructionsSyncTextBox_KeyUp(object sender, KeyEventArgs e)
{
int linecount = InstructionsSyncTextBox.GetLineFromCharIndex(InstructionsSyncTextBox.TextLength) + 1;
if (linecount != maxLC)
{
InstructionsLineNumberSyncTextBox.Clear();
for (int i = 1; i < linecount + 1; i++)
{
InstructionsLineNumberSyncTextBox.AppendText(Convert.ToString(i) + ""\n"");
}
maxLC = linecount;
}
}";
Regex r = new Regex("\r", RegexOptions.Multiline);
int lines = r.Matches(stringFromTextBox).Count;
//You'll need to run this line every time the user presses a key
}
}

Categories