Placing A Thousand Lines Of 24 Integers In A Listview - c#

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);
}
}

Related

Loading textfile

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);
}
}
}
}

Microsoft Visual Studio Arrays at Runtime

My instructions are: "Create a form that will display a running total of numbers a user enters." - to do this I've created a form with two text boxes (one for the number of values in the array and the other for the values in the array), a button to display it, and a label for it all to be displayed it. The issue is, is that my values aren't showing up - at all. My code is as below:
(** NOTE: I'm attempting to get the array to display in my label. txtInput is the inputted values and txtArrayValues is the number of elements.)
namespace Running_Total
{
public partial class frmEnter : Form
{
public frmEnter()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int intNumber = Convert.ToInt32(txtArrayValues.Text);
string[] strArray;
strArray = new string[intNumber];
int i;
string j = "";
for (i = 0; i < intNumber; i++)
{
j = Convert.ToString(txtInput.Text);
strArray[i] += j;
}
lblDisplay.Text = strArray + " ";
}
}
}
Before, when I'd put lblDisplay.Text += j + " ";, it showed up in the label, but didn't pay any attention to the amount of elements the code was supposed to have. (Edit: this no longer works in my code.) (As is indicated in the title, I'm working with C# through Microsoft Visual Studio.)
It strongly depends on the fashion how the user inputs the numbers.
1) If he fills the textbox once with numbers and then presses the button to display them in the other box, it would suffice to use a string array catch the input and add it to the textbox or label that displays it. If he deletes the numbers in the input box and types new ones you could just repeat this step
namespace Running_Total
{
public partial class frmEnter : Form
{
// declare your Array here
string [] array = new string[1000];
int count = 0;
public frmEnter()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
// save input
array[count] = inputTextBox.Text;
count++;
// display whole input
string output = "";
for(int i = 0;i < count; i++)
{
output += array[i];
}
// write it the texbox
outputTextBox.Text = output;
}
}
Does that answer your question or do you have another input pattern in mind?
Looking at your code, I realized that you want to display same number enteted in txtInput text repeatedly up to as many times as a number entered in a txtArrayValues.Text. So for example txtArrayValues. Text = "5" and txtInput.Text="2", your code will yield result "2,2,2,2,2". If that is what you want then the following code will achieve that.
using System.Linq;
namespace Running_Total
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int len, num;
if (int.TryParse(txtArrayValues.Text, out len) &&
int.TryParse(txtInput.Text, out num))
{
lblDisplay.Text = string.Join(",", new string[len].Select(x => txtInput.Text));
}
}
}
}

How to increment textbox when a button is pressed in another page

So this is really bugging me - I am trying to make it that everytime a item is chosen in one page a textbox in another page should be incremented.
If items are greater than 0 txtbox should increment textbox
if ((Menu.VanillaQ > 0) || (Menu.LCQ > 0) || (Menu.ChocQ > 0) )
{
Orders++;
NoOfOrder.Text = Orders.ToString();
}
}
Menu Class declaring variables
public static double VanillaQ;
public static double LCQ;
public static double ChocQ;
//Code for one Item
if (VanillaQ <= 100)
{
VanillaQ = VanillaQ+1;
txtAmount.Text = VanillaQ.ToString(); //Gets quantity of each item and sets it as a string
}
Make new order btn-sets all variables to 0
private void Orderbtn_Click(object sender, RoutedEventArgs e)
{
Menu.BanQ = 0;
Menu.VanillaQ = 0;
Menu.StrawQ = 0;
Menu.MintQ = 0;
Menu.ChocQ = 0;
Menu.CurryQ = 0;
Menu.EggQ = 0;
Menu.LagerQ = 0;
Menu.LCQ = 0;
Frame.Navigate(typeof(Type));
}
Right now it only increments one time no matter how many loops I take. And after I press the Make new order button the variables are all resetted to 0 therefore after if item is chosen variable will be greater than 0 and textbox should be incremented. But it only increments once which really confuses mr :s

C# display components based on name

Is it possible to set a components visible attribute based on its name?
I have 12 "master" components (comboboxes) if you want to call them that and based on the selection in these I want to display anywhere from 1 to 16 textboxes. These are named in numeric order such as combobox1_textbox_0, combobox1_textbox_1 and so on. What I would like to do ideally is take the index of the combobox and pass it as a parameter to a method that sets the textboxes visible attribute to visible/hidden depending on the index passed into the method.
Is this possible? in pseudocode or what you call it I would like it to work something like this:
private void methodToSetVisibleAttribute(int indexFromMainComboBox)
{
for(int i = 0; i < 15; i++)
{
if(i < index)
{
combobox1_textbox_+i.Visible = true;
}
else
{
combobox1_textbox_+i.Visible = false;
}
}
}
I could do panels or something for the choices but seeing as all the selections from the combobox will use the same textboxes but in different amounts it seems like alot of work to make a panel for every possible selection not to mention difficult to expand the program later on.
Assuming you are using Windows Forms and not WPF, you can use ControlCollection.Find() to find controls by name:
var textBox = this.Controls.Find(string.Format("combobox1_textbox_{0}", i), true).OfType<ComboBox>().FirstOrDefault();
if (textBox != null)
textBox.Visible = (i < index);
else
Debug.Assert(false, "textbox not found"); // Or throw an exception if you prefer.
I'll suggest an alternative to your approach, maybe not quite what you're looking for:
Place your combo boxes in a List<ComboBox> and you can access them by an index number.
List<ComboBox> myCombos = new List<ComboBox>();
for (int i = 0; i < 16; i++)
{
ComboBox cb = new ComboBox();
//do what ever you need to do here. Set its location, add items, etc.
Form1.Controls.Add(cb); //Alternatively add it to another container.
myCombos.Add(cb); //Now it's in a list.
}
Modify them like this:
for(int i = 0; i < 15; i++)
{
if(i < index)
{
myCombos[i].Visible = true;
}
else
{
myCombos[i].Visible = false;
}
}
Or even more succintly:
for(int i = 0; i < 15; i++)
{
myCombos[i].Visible = i < index;
}

How to get correct answer for quiz when randomly assigning answers, from a dataset, to a buttons text attribute

I have a quiz that I'm writing and I'm using 4 buttons text attributes to display the multiple choice answers. 1 is correct, the other 3 are wrong.
The answers are from my dataset and then randomly assigning the answers to the buttons text attributes, when the user selects an answer then it moves along to the next question and doing the same thing, as it should.
But what I can't seem to figure out is, since I'm assigning the answers randomly, how do I keep track of answer that was selected? Here is the code...
Label1.Text = ds.Tables[0].Rows[myNum]["Question"].ToString();
string[] array = new string[4] {
ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString(),
};
// randomize the ordering of the items
System.Random rnd = new System.Random();
array = array.OrderBy(x => rnd.Next()).ToArray();
// each time you run this, the correct answer will be in a different place:
btn1.Text = array[0];
btn2.Text = array[1];
btn3.Text = array[2];
btn4.Text = array[3];
myNum = myNum + 1;
if (myNum == numOfRows)
Response.Redirect("~/Results.aspx");
I have tried this...
ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString() + "1",
ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString() + "0",
ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString() + "0",
ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString() + "0",
and as expected it didn't work at all, but I tried it any ways.
Any ideas?
Thanks
When you shuffle your array you lose track of the correct solution. This is not what you want. You should always be able to tell from your code which button will be assigned the correct answer. This does not mean you should know which id this button has, but how it gets assigned.
One thing you could do for example is shuffle an array of your button objects, and always assign your correct answer to the first index in that array.
So you create an array of your button objects, shuffle it. You assign the correctAnswerClick handler and the answer string to the first index (0) in that array. You assign the falseClick and wrong answers to index 1, 2 and 3. This way you always know that the correct button has the proper event handler.
The code below is what you want to achieve in Winforms (I don't have ASP installed in VS.Net atm) but it should be easily translated to ASP.Net I think.
button1 to button4 are named btn1 to btn4 in your case.
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
var btnns = new List<Button>();
btnns.Add(button1);
btnns.Add(button2);
btnns.Add(button3);
btnns.Add(button4);
//Shuffle the list
Shuffle<Button>(ref btnns);
//Add an event handler for success to your first button
btnns[0].Click += successClick;
btnns[0].Text = "Correct";
for (int i = 1; i < btnns.Count; i++)
{
btnns[i].Click += failedClick;
btnns[i].Text = "Wrong " + i;
}
}
private void failedClick(object sender, EventArgs e)
{
//Add a true value to the viewstate list
AddAnswer(true);
}
private void successClick(object sender, EventArgs e)
{
//Yay, it's correct
AddAnswer(false);
}
public void AddAnswer(bool correctornot)
{
//I am not 100% sure about the code below (not tested), but it should give you an idea
if (Session["listOfAnswers"] != null)
{
var currentList = (List<bool>) Session["listOfAnswers"];
currentList.Add(correctornot);
Session["listOfAnswers"] = currentlist;
}
else
{
var currentlist = new List<bool>();
currentlist.Add(correctornot);
Session["listOfAnswers"] = currentlist;
}
}
public void Shuffle<T>(ref List<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
Answer taken from here: Randomize a List<T>

Categories

Resources