When the first option is selected in a combo box I wish for my program to subtract consecutive strings from the one before.
Eg. The second value from the first,the third from the second, the fourth from the third and so on to the limit of 40.
I tried this but it just reads the actual list with no calculation
private void comboBoxOptions_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxOptions.SelectedIndex == 0)
{
string population = #"U:\My Documents\4.Bus App\Assignment 5\irishPopulation.txt";
const int SIZE = 40;
int[] numbers2 = new int[SIZE];
int index = 0;
StreamReader inputFile = new StreamReader(population);
while (index < numbers2.Length && !inputFile.EndOfStream)
{
numbers2[index] = int.Parse(inputFile.ReadLine());
index++;
}
textBoxAnswer.Text = File.ReadAllText(#"U:\My Documents\4.Bus App\Assignment 5\irishPopulation.txt"); //Puts file in textbox
textBoxAnswer.ScrollBars = ScrollBars.Vertical; //Gives text a scroll bar
inputFile.Close();
}
Related
I have questions how can I set the quantity of numbers in the result box based on the selected value in dropdown
This is my code
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text))
{
string totalListNumber = "";
for (double x = Convert.ToDouble(TextBox1.Text); x <= Convert.ToDouble(TextBox2.Text); x++)
{
totalListNumber += x + "\n";
}
TextBox3.Text = totalListNumber;
}
Firstly you need to create a random number between your two values.
System.Random roll = new Random();
int nextRandom = roll.Next(minValue, maxValue);
Your combo box has an event called SelectedIndexChanged that will trigger when the user changes your combo selection.
In your SelectedIndexChanged code you should then put something like:
private void cmbQuantities_SelectedIndexChanged(object sender, EventArgs e)
{
System.Random roll = new Random();
int nextRandom;
// turn the two textBoxes into two doubles minValue and maxValue
if ((double.TryParse(TextBox1.Text, out double minValue) == false) || (double.TryParse(TextBox2.Text, out double maxValue) == false)) return;
// get the number of items to display or exit if it is not a valid number (return)
if (int.TryParse(cmbQuantities.Text, out int randomsToDisplay) == false) return;
string totalListNumber = String.Empty;
for(int i = 0; i < randomsToDisplay; i++)
{
nextRandom = roll.Next(minValue, maxValue);
totalListNumber += nextRandom.ToString() + "\n";
}
TextBox3.Text = totalListNumber;
}
There are a lot of other boosts you should do (such as using a listView etc), but this will get you what you want.
You should also try looking at using a datasource for the comboBoxQuantity that has an int value and string description so that selecting the combo item gets you the quantity value as an int automatically (or even just use a textbox!)
Avoiding duplicate numbers
As the Random class will produce duplicate numbers you will need to store your random rolls in a list and then check the list every time a new number is rolled.
The HashSet class allows fast lookups by a key (your random number in this case).
So:
private void cmbQuantities_SelectedIndexChanged(object sender, EventArgs e)
{
System.Random roll = new Random();
int nextRandom;
HashSet<int> rolledRandoms = new HashSet<int>();
// turn the two textBoxes into two doubles minValue and maxValue
if ((double.TryParse(TextBox1.Text, out double minValue) == false) || (double.TryParse(TextBox2.Text, out double maxValue) == false)) return;
// get the number of items to display or exit if it is not a valid number (return)
if (int.TryParse(cmbQuantities.Text, out int randomsToDisplay) == false) return;
string totalListNumber = String.Empty;
for(int i = 0; i < randomsToDisplay; i++)
{
nextRandom = roll.Next(minValue, maxValue);
// keep rolling until the nextRandom value is not in the rolledRandoms list
while (rolledRandoms.ContainsKey(nextRandom))
nextRandom = roll.Next(minValue, maxValue);
rolledRandoms.Add(nextRandom);
totalListNumber += nextRandom.ToString() + "\n";
}
TextBox3.Text = totalListNumber;
}
I have 2 textboxes for my list box.
start number and
finish number
I typing numbers and press "Aktar" button, then I want to add to listbox like below but how can I do that
I want to get a result like below
Adding numbers from start number to end number to ListBox:
private void btnAktar_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
var a = int.Parse(textBox1.Text);
var b = int.Parse(textBox2.Text);
var s = string.Empty;
for (var x=a;x<=b;x++)
{
s += x.ToString();
listBox1.Items.Add(s);
}
var chars = s.ToCharArray();
Array.Reverse(chars);
var reversedS = new string(chars);
for(var i = 1; i < reversedS.Length; i++)
{
var item = reversedS.Substring(i, reversedS.Length - i);
listBox1.Items.Add(item);
}
}
Result:
Problem in short: Load saved map that was saved as an textfile where 0 = empty button/tile, 1 = wall, 2 = character and it back up on another form.
Longer more detailed explanation:
I have been working on a winform game for a bit, I know it isn't the best way to make a game but I am just trying to get accustomed. Currently I have two forms, one to create a map, another to load it up. On my map creation form I am able to say the length and width of my map, when I generate it, it displays tiles(that are buttons) with the length and width dimensions specified( 3 buttons wide, 4 buttons long.)
Now I am able to save it as numbers that were given values for that certain image ( 0 is for no image just the button, 1 is for a button with an wall, 2 is for a button with a character.). What I am trying to do now is read the text file and load up the tiles with the correct dimensions and image that was originally given.
My images are placed onto radio buttons which determine which image to play, I did tags for this
public SaveForm()
{
InitializeComponent();
rNoImage.Tag = 0;
rNoImage.Click += Check;
rCharacter.Tag = 1;
rCharacter.Click += Check;
rWall.Tag = 2;
rWall.Click += Check;
}
private void square_Click(object sender, EventArgs e)
{
Map square = (Map)sender;
Map.Type = (MapType)selected;
switch (selected)
{
case 0:
square.Image = null;
break;
case 1:
square.Image = Properties.Resources.Character;
break;
case 2:
square.Image = Properties.Resources.Wall;
break;
}
}
private void Check(object sender, EventArgs e)
{
RadioButton toolBtn = (RadioButton)sender;
selectedTool = (int)toolBtn.Tag;
}
When saving I have done the following:
private void saveButton(object sender, EventArgs e)
{
SaveFileDialog sfg = new SaveFileDialog();
sfg.Filter = "Game File(*.game)|*.game";
if (sfg.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfg.FileName))
{
sw.WriteLine($"{rows},{cols}");
foreach (Map square in (pnlGameBoard.Controls))
{
sw.WriteLine(square.GetString());
}
var output = MessageBox.Show("saved", "saved success", MessageBoxButtons.OK);
}
}
}
I have a component class set up for this called Map in this I have an enum to show the types
public enum MapType
{
None,
Character,
Wall,
}
Now I have my map being made as an Button, when clicked based on selected radio button image changes on the button.
public partial class Map : Button
{
int row;
int col;
public MapType Type { get; set; }
const int OFFSET = 20;
const int MapSize = 50;
public Map()
{
}
public Map(int row, int col)
{
this.row = row;
this.col = col;
this.Size = new Size(MapSize, MapSize);
this.Location = new Point(OFFSET + col * MapSize, OFFSET + row * MapSize);
Type = MapType.None;
}
public string GetString()
{
return $"{(int)Type}";
}
}
So I am able to save it, but my issue now is loading it up on the second form which I am struggling to do.
What I have managed so far is:
private void openButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofg = new OpenFileDialog();
ofg.Filter = "Game File(*.game)|*.game;"
if(ofg.ShowDialog() == DialogResult.OK)
{
File.ReadAllLines(ofg.FileName);
//Not Sure what to do next here
}
}
Apologize for the lengthy post but I wanted to make sure that I am clear enough, thanks.
The layout for the textfile that I saved would be:
3,3
1
1
1
0
2
0
1
1
1
3,3 represents the length and width that was chosen, I will most likely remove this as I am only trying to read the numbers below, top row is wall,wall,wall(1,1,1), middle row is empty button, character, empty button, bottom row is wall,wall,wall.
I have looked at some different examples here that involve reading 2D matrixes from files to 2D int arrays but I am not sure how to actually implement this in my above code or how it works.
You've created a way to represent a Map as a string, but not the other way around. One way to create a Map from a string is to write a public static Map Parse(string input) method that takes in a string and returns a Map. One tricky part is that we will also need to pass in the row and col, since those are private fields and not settable outside of the constructor.
For example:
public class Map : Button
{
// Existing code exluded from this example
public static Map Parse(string input, int row, int col)
{
if (input == null) return null;
int typeVal;
if (!int.TryParse(input, out typeVal))
{
throw new ArgumentException("input must be a valid integer");
}
// Return a new map with row, col, and Type
return new Map(row, col) {Type = (MapType) typeVal};
}
}
Now that we can create a Map with the proper Type from a string (along with the row and col), we can create a couple of loops: one to loop through each row, and on each row we loop through each column, creating a Map and adding it to our panel:
// You might need to set some standard sizes for the Map controls
private int mapHeight = 50;
private int mapWidth = 300;
// Not sure where these are actually defined
private int rows;
private int cols;
private void openButton_Click(object sender, EventArgs e)
{
var ofg = new OpenFileDialog {Filter = "Game File(*.game)|*.game;"};
if (ofg.ShowDialog() == DialogResult.OK)
{
// Read all our lines into an array
var lines = File.ReadAllLines(ofg.FileName);
// And now do the opposite of how we created the text file:
// First, set the rows and cols based on the first line
// (some validation should be done here, but this works with "3,3")
var rowsCols = lines[0].Split(',');
int.TryParse(rowsCols[0], out rows);
int.TryParse(rowsCols[1], out cols);
// Next, create Maps from the rest of the lines and add them to our controls
// Note we should validate that lines.Length = rows * cols + 1
var line = 1; // This gets incremented below, so we read each line
for (int row = 0; row < rows; row ++)
{
for (int col = 0; col < cols; col++)
{
// Create a map from the line, row, and column using our new method
var map = Map.Parse(lines[line++], row, col);
// Set the layout by rows and columns (?)
map.Width = mapWidth;
map.Height = mapHeight;
map.Left = (col + 1) * mapWidth;
map.Top = (row + 1) * mapHeight;
// Hook up the Click event so our images load on click
map.Click += square_Click;
// Add the control to our panel
pnlGameBoard.Controls.Add(map);
}
}
}
}
I am trying to print a list of occurrences of each letter in thee text inputed by the user but the textbox only shows the last letter.
private void button1_Click(object sender, EventArgs e)
{
//disable the text box so text cannot be entered until reset is pressed
textBox3.Enabled = false;
//make a list containing the alphabets
List<string> Alphabets = new List<string>();
Alphabets.Add("A");
Alphabets.Add("B");
Alphabets.Add("C");
Alphabets.Add("D");
Alphabets.Add("E");
Alphabets.Add("F");
Alphabets.Add("G");
Alphabets.Add("H");
Alphabets.Add("I");
Alphabets.Add("J");
Alphabets.Add("K");
Alphabets.Add("L");
Alphabets.Add("M");
Alphabets.Add("N");
Alphabets.Add("O");
Alphabets.Add("P");
Alphabets.Add("Q");
Alphabets.Add("R");
Alphabets.Add("S");
Alphabets.Add("T");
Alphabets.Add("W");
Alphabets.Add("X");
Alphabets.Add("Y");
Alphabets.Add("Z");
//make a while loop to cycle through alphabets loop
int i = 0;
while (i < Alphabets.Count)
{
//assign value in the list Alphabets
string SearchFor = Alphabets[i];
//access textbox and make it to upper small small and captital are the same
string SearchIn = textBox3.Text.ToUpper();
//list to count the number of instances used for each letter
List<int> FoundCount = Search(SearchFor, SearchIn);
//if statement so only letters that occor more than 0 times are displayed
if (FoundCount.Count > 0)
{
//string to display the number of occorances
//convert to toString so it can be displayed in the TextBox
string Counts = Alphabets[i] + ": " + FoundCount.Count.ToString();
//create a message box to display the output
//MessageBox.Show(Counts);
textBox4.Text = String.Join(Environment.NewLine, Counts);
}
//adds 1 each time as long as i <alphabet.count
i++;
}
}
//List takes 2 arguements (SearchFor, SearchIn) Results can be passed to FoundCounts and number of occrances can be calculted
List<int> Search(string Target, string Subject)
{
//List to count the number of occarances for each letter
List<int> Results = new List<int>();
//for loop for comparison (counting occarances) to compare each letter in textbox to each letter in alphabets
for (int Index = 0; Index < (Subject.Length - Target.Length) + 1; Index++)
{
//if to calculate the number of times a letter is used.
if (Subject.Substring(Index, Target.Length) == Target)
{
//adds the number in index to the list Result
Results.Add(Index);
}
}
return Results;
}
i made multiline as true but that didnt work
I'm pretty sure the issue with your code is here:
textBox4.Text = String.Join(Environment.NewLine, Counts);
You're overwriting the text every time, instead you should do:
textBox4.Text += String.Join(Environment.NewLine, Counts);
This isn't a direct answer to the question, but this might be valuable for the OP.
This code does everything that the original code did (and also fixes the issue raised in the question):
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var query =
from c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let count = SearchIn.Count(x => x == c)
select String.Format("{0}: {1}", c, count);
textBox4.Text = String.Join(Environment.NewLine, query);
}
There you go, a version that uses lists. :-)
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList();
var query =
from c in alphabet
let matches = SearchIn.Where((x, n) => x == c).ToList()
select String.Format("{0}: {1}", c, matches.Count());
textBox4.Text = String.Join(Environment.NewLine, query);
}
I have placed a ListView on my main form.
I put 24 columns in it
I set the view to details
I have an array of integers like this
public static int[] myArrayOfIntegers = new int[24];
public static bool TheArrayIsNowReady = false;
int i;
int j;
int k;
string UserSeesThis;
Now for my request for help, please. There are 151 properties and 233 Methods associated with a ListView. Could someone please help me to understand how to place my 24 integers in this listview for the user to see them ?
if (TheArrayIsNowReady)
{
for (i = 0; i < 24; i++)
{
UserSeesThis = myArrayOfIntegers[i].ToString();
listView1._____what___do___I___put___here___[i] = UserSeesThis;
}
}
After doing one line, I'm going to have to put 500 more lines in the list box, and let the user scroll back through them. (We're hunting bogus numbers, if it matters)
In my dream app, I'll let the user scroll back five or six thousand lines.
The user is going to run a test, and an external box will send the PC 500 sets of 24 numbers. I want to put those on the screen for the user to see. I would like to be able to handle the same five and ten times over.
1) Create a listviewitem, ListViewItem item = new ListviewItem("firstvalue");
2) Create subitems for each column, item.SubItems.add("value");
3) Add item to list, listView1.Items.Add(item);
public static int[] myArrayOfIntegers = new int[24];
public static bool TheArrayIsNowReady = false;
int i, j, k;
string UserSeesThis = "?";
ListViewItem item;
private void Form1_Load(object sender, EventArgs e)
{
TheArrayIsNowReady = true;
if (TheArrayIsNowReady)
{
for (i = 0; i < 24; i++)
{
myArrayOfIntegers[i] = i;
if (i == 0) { item = new ListViewItem(myArrayOfIntegers[0].ToString()); }
item.SubItems.Add(myArrayOfIntegers[i].ToString());
UserSeesThis = "?";
}
listView1.Items.Add(item);
}
}