Change label text with an array - c#

So, I simply want to dynamically change my what label is currently edited through an array, to achieve as little code as possible.
This is what it looks like right now:
string[] poängLabels = new string[10];
for (int i = 3; i <= 9; i++)
{
poängLabels[i] = ("label{0}.Text" + i);
}

You should do it like this:
poängLabels[i] = ((Label)this.Controls.Find("label" + i)).Text;
or
poängLabels[i] = ((Label)this.Controls["label" + i]).Text;

You have to be able to enumerate controls somehow, putting (or having them) in the array is one option:
var result = new { label1, label2, ... }.Select(label => label.Text).ToArray();

Related

c# Fill a listview with items from a richtextbox (each 5 lines into columns)

I have a list view and a richtextbox.
This richtextbox has data like below. And I want to input the first 5 lines in one row and 5 columns like below.
richtextbox example and List view example
I have the below code so far
for ( int i = 0; i < richTextBox1.Lines.Count(); i++)
{
string[] arry = new string[5];
ListViewItem itms;
arry[0] = richTextBox1.Lines[i];
arry[1] = richTextBox1.Lines[i+1];
arry[2] = richTextBox1.Lines[i + 1];
arry[3] = richTextBox1.Lines[i+2];
arry[4] = richTextBox1.Lines[i+3];
itms = new ListViewItem(arry);
listView1.Items.Add(itms);
}
But it is not giving me the desired output, as it repeats itself over and over like seen here
Undesired Output
Kindy let me know where I am going wrong
Your for loop is going line by line, not by groups of 5 lines.
Change it to this:
for ( int i = 0; i < richTextBox1.Lines.Count(); i += 5)

Button Click action does not register itself the method it is assigned to

I've got myself into a little bit of a jam. As I tried to code the entire alphabet into my app, I didn't really feel like typing the letters in one by one, so I used ASCII characters and used a for-loop and inserted them as buttons. So, now I need those buttons to click according to my needs, but somehow I cant seem to figure out what is the problem with the issue. The code is as follows:
private void Hangman_OnLoaded()
{
const int btnSize = 35;
var c = 0;
for (var i = 65; i <= 90; i++)
{
var btn = new Button {
Content = (char) i,
Click += GuessClick()
};
btn.Width = btn.Height = btnSize;
var margin = btn.Margin;
margin.Left = c += 37;
btn.Margin = margin;
GridMain.Children.Add(btn);
}
}
private void GuessClick(object sender, EventArgs e) {
var choice = sender as Button;
if (choice == null || !copyCurrent.Contains(choice.DataContext.ToString())) return;
var temp = copyCurrent.ToCharArray();
var find = copyCurrent.ToCharArray();
var guessChar = choice.DataContext.ToString().ElementAt(0);
for (var index = 0; index < find.Length; index++) {
if (find[index] == guessChar) {
temp[index] = guessChar;
}
}
copyCurrent = new string(temp);
DisplayTheWord();
}
I will take a stab at "Psychic Debugging" this code. There are lots of things that can be improved, changed, etc, but I am guessing this is where you may be having an issue:
var temp = copyCurrent.ToCharArray();
var find = copyCurrent.ToCharArray();
var guessChar = choice.DataContext.ToString().ElementAt(0);
for (var index = 0; index < find.Length; index++) {
if (find[index] == guessChar) {
temp[index] = guessChar;
}
}
copyCurrent = new string(temp);
No matter what the guessChar is, at the end of this block of code copyCurrent will be unchanged (as far as what the actual string content of copyCurrent is). First you make two arrays that are identical. Then you are looping through the find array looking for the guessChar. If you find the guessChar then you are "modifying" the temp array to have guessChar at the very same index where you found it in find. Since both arrays are identical, the end result is that no "change" takes place. Once you have executed the loop you are creating a new string from the temp array, but since both find and temp are identical and unchanged after this loop, you effectively are making a new string that is identical to the one you started with. I don't know what you are expecting this code to do, but I am assuming this is not it.
I am going to assume (from the load method name) that this is a game of hangman and that at the outset of the game copyCurrent has some content like "????" and that you have some other variable, maybe called answer and it would have the content, for example, "food". If that is the case, then you would just need to modify these two lines:
var temp = copyCurrent.ToCharArray();
var find = answer.ToCharArray();

Button Array using String and Integer C#

I want to make button array that include string and integer. I have 30 buttons and named B1, B2, ...., B30 and I want to change their color depend on the counter value. How can I do that? These are what I have done and I stuck
for(Cnt = 0; cnt < 30; cnt++)
{
Button[] Tombol = new Button[]{"B"+(cnt+1)};
Tombol[cnt].BackColor = Color.Red
}
The Control (custom) initialization in the Form (in your case, the Control being a Button) requires more than a simple declaration. Apart from giving name (which you do), two other important things to do are:
To add it to the Control parent
To locate it nicely
Thus, adding those considerations to the Button you are to create, you could do something like this
int noOfBtns = 30;
Button[] Tombols = new Button[30]; //actually, you may not need this at all
for (int cnt = 0; cnt < numOfBtns; cnt++)
{
Button tombol = new Button();
tombol.BackColor = Color.Red;
tombol.Location = new Point(5, cnt * 25); //Read (2) please formulate this more properly in your case
tombol.Name = "B" + (cnt + 1).ToString();
// others like size (maybe important depending on your need), color, etc
this.Controls.Add(tombol); //Read (1) this refers to the `Form` if the parent control you want to put your button to is `Form`. But change the `this` as you see fit
Tombols[cnt] = tombol; //again, actually you may not need this at all
}
Take care of how you formulate the location of your button, very important. The example I gave above is really simple formulation, which might not fit if your number of buttons grow large. But that gives you the basic idea on how important it is to set the location of the Button right.
You may need the array of Button at all, unless for some reason you want to list it. But even you want to list it, you should use List and List.Add instead of Array.
I suggest using Linq to generate the array:
Button[] Tombol = Enumerable
.Range(0, 30)
.Select(i => new Button() {
Text = String.Format("B{0}", i + 1),
BackColor = Color.Red,
//TODO: compute desired color as function of "i" like
// BackColor = Color.FromArgb(i * 8, 255 - i * 8, 128),
//TODO: assign Parent, Location, Size etc. like this:
// Parent = this,
// Location = new Point(10 + 40 * i, 10),
// Size = new Size(35, 20),
})
.ToArray();
I mean like this:
Button[] Tombol = new Button[30];
for(cnt = 0; cnt < 30; cnt++)
{
Tombol[cnt] = new Button
{
Text = "B" + (cnt+1),
BackColor = Color.Red
};
}
First you create the array and in the for loop you instantiate the actual buttons one by one.
You have to initialize the button array first
int numOfBtns = 30;
Button[] Tombol = new Button[numOfBtns];
and after you can fill required items
for (int cnt = 0; cnt < numOfBtns; cnt++)
{
// Name, Content, Foreground .. whatever
Tombol[cnt].Name = "B" + (cnt + 1);
}
At the moment you are recreating your array on each loop of your code rather than creating the array outside of the loop and then adding buttons to it in the loop.
In addition all your buttons are being created in the same position, so they are on top of each other meaning you can only see one of them.
Try something like this, based on a modified version of the code from this previous answer which creates the buttons, adds them to a list you can search and the sets the positions of the buttons too:
int top = 50;
int left = 100;
var buttons = new Dictionary<string, Button>();
for (int i = 0; i < 30; i++)
{
Button button = new Button();
buttons.Add("B"+i, button);
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
button.BackColor = Color.Red;
}
You can then refer to an individual button later with the code:
buttons["B3"].BackColor= Color.Green;

How to read values from textboxes I created in one form and send them to another form?

So, I created this textboxes in a form2;
System.Windows.Forms.TextBox[] someTb = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; ++i)
{
sombeTb[i] = new TextBox();
textos[i].Location = new System.Drawing.Point(60, 84 + i * 35);
this.Controls.Add(textos[i]);
}
I need to acces to this TextBoxes (someTb) and send them to another Form
Since you already have them in an array, you can just pass that array to another form. Declare a public TextBox[] TextBoxes { get; set; } on the new form, when the form is instanced, assign the array (or a copy of the array) to the public property. Otherwise, you could do similar with a Dictionary<int, string> that uses the array index as the int key portion, and the TextBox Value in the string value portion. Then pass that collection along to the new form.
Probably the most simple answer would be to have a static class in your project that has static members of TextBoxs and read/write to the static variable from either form.
Finally I used the Name property to calle the TextBox whenever i want.
System.Windows.Forms.TextBox[] someTb = new System.Windows.Forms.TextBox[10];
for (int i = 0; i < 10; ++i)
{
sombeTb[i] = new TextBox();
someTb[i].Location = new System.Drawing.Point(60, 84 + i * 35);
this.Controls.Add(someTb[i]);
someTb[i].Name = "someName" + i.ToString();
}
And then I can acces to its methods like this
this.Controls["someName" + i].Method
It´s not the best way, but since I was in a hurry it was the one I used.

Array values from textboxes

I have a 16 element int array and 16 textboxes (textBox1, textBox2 ....) that look like 4x4 matrix. Is there any way to put textboxes values to every array element not using code like this:
array[1] = (int)textBox1.Text;
array[2] = (int)textBox2.Text;
One possibility would be to store the references to the TextBox instances in an array.
TextBox[] Boxes;
And then use a 'for' loop to populate the values.
for (int i = 0; i < 16; i++)
{
array[i] = (int)Boxes[i].Text;
}
You could use a function to get the text box's text as an integer using it's "index" from the form's control collection:
int GetBoxText(int index)
{
return Convert.ToInt32(this.Controls["textBox" + i.ToString()].Text);
}
Note that this has no error checking of any kind. You could add some if you wanted to. All this does is get the text of the control named textBox + whatever i is from the form's control collection and convert it to an integer.
IMHO the best way to design is by the way it's meant to be. In particular, rectangular/multidimensional arrays may be useful in this scenario:
public partial class Form1 : Form {
TextBox[,] textBoxes;
int[,] values;
public Form1() {
InitializeComponent();
textBoxes = new TextBox[4, 4];
values = new int[textBoxes.GetLength(0), textBoxes.GetLength(1)];
for(int r = 0; r < textBoxes.GetLength(0); r++) {
for(int c = 0; c < textBoxes.GetLength(1); c++) {
values[r, c] = int.Parse(textBoxes[r, c].Text);
}
}
}
}

Categories

Resources