Easiest way to display 2dimensional array of values on buttons - c#

I am looking for optymalize code with displaying 2dimensional array of values on buttons.
I have created grid of buttons like that:
http://screenshot.sh/m2eZscO4i0fXq
and I am actually displaying values of array on this buttons using this code:
button1.Text = board.gameBoard[0, 0].getValue().ToString();
button2.Text = board.gameBoard[0, 1].getValue().ToString();
button3.Text = board.gameBoard[0, 2].getValue().ToString();
button4.Text = board.gameBoard[0, 3].getValue().ToString();
button5.Text = board.gameBoard[1, 0].getValue().ToString();
...
button15.Text = board.gameBoard[3, 2].getValue().ToString();
button16.Text = board.gameBoard[3, 3].getValue().ToString();
Is there easier way to do that? It's working now (http://screenshot.sh/mMDP9pvcC7WOk), but it isn't the best way to do this thing I think. Can somebody show me how do that better?

You can create your buttons dynamically and during creating put the text what you want to Button.Text.
It will be something like:
// array of your buttons (it's not necessary)
var buttons = new Button[4,4];
void SomeMethod()
{
for(var x = 0; x < 4; x++)
{
for(var y = 0; y < 4; y++)
{
var newButton = new Button();
// put your text into the button
newButton.Text = board.gameBoard[x, y].getValue().ToString();
// set the coordinates for your button
newButton.Location = new Point(someCoordinateX, someCoordinateY);
// store just created button to the array
buttons[x, y] = newButton;
// add just created button to the form
this.Controls.Add(newButton).
}
}
}
then, use this method somewhere on initialization step to create and initialize your buttons. The buttons array could be used lately if you will need to modify your buttons somehow.
Hope it will help.

Related

Create multiple ListBoxes - Windows applications forms

I'm trying to create multiple ListBoxes with different id's.
I want to do something like this:
int count = 0
for(int i = 0; i < 10; i++){
ListBox count = new ListBox();
count++;
}
The question is: How to create create multiple ListBoxes?
A Listbox is a control that should be added to the Controls collection of its container. I suppose that this is your form and you will call this code inside some kind of event of your form (like Form_Load for example) or better inside the constructor of the form after the call to InitializeComponents()
for (int i = 0; i < 10; i++)
{
// Create the listbox
ListBox lb = new ListBox();
// Give it a unique name
lb.Name = "ListBox" + i.ToString();
// Try to define a position on the form where the listbox will be displayed
lb.Location = new Point(i * 50,0);
// Try to define a size for the listbox
lb.Size = new Size(50, 100);
// Add it to the Form controls collection
// this is the reference to your form where code is executing
this.Controls.Add(lb);
}
// Arrange a size of your form to be sure your listboxes are visible
this.Size = new Size(600, 200);
You've mixed up the int and ListBox types, and as for ID's, Name would be sensible choices:
So how about something like this:
for (int i = 0; i < 10; i++)
{
ListBox listBox = new ListBox();
listBox.Name = i.ToString();
// do something with this listBox object...
}

Dynamically add components to windows form C#

I am trying to add a list of Strings to be used as the text component of labels on a windows form. Below is the code i am using to do this. I have it generating a message box to show me what is being created, but when i add them to the form, only the first string is ever shown on the form, despite a message box popping up for each string indicating the list is populated correctly. Any help would be great.
List<Label> labelList;
public void ShowDialog(List<String> columns)
{
labelList = new List<Label>();
Form updateDialog = new Form();
updateDialog.Width = 500;
updateDialog.Height = 500;
for (int i = 0; i < columns.Count(); i++ )
{
//Label label = new Label() {Text=columns[i].ToString() };
labelList.Add(new Label() {Text=columns[i].ToString()});
}
for (int j = 0; j < labelList.Count(); j++ )
{
updateDialog.Controls.Add(labelList[j]);
MessageBox.Show(labelList[j].Text.ToString());
}
You need to set the location of the created labels. They are positioned on top of each other at location (0, 0).
Controls are being added to the form, but they are not visible to you. Just set the different location for each Label and you'll see them.
You can also precise your code by using 1 loop instead:
int yAxis = 10;
for (int i = 0; i < columns.Count(); i++ )
{
//create label
Label newLbl = new Label() {Text=columns[i].ToString()};
newLbl.Location = new Point(10, yAxis * i); //will create a column of all labels, you can use your oown logic too
//add to list
labelList.Add(newLbl);
//add to form
updateDialog.Controls.Add(newLbl);
//show on msg box
MessageBox.Show(newLbl.Text.ToString());
}

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Is there any way to dynamically create and display 'n' Labels with 'n' corresponding Textboxs when we know value of 'n' after for example, clicking "Display" button.
Let me know if anything make you don't understand my question. Thank you!
I am working with VS C# Express 2010 Windows Form.
I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.
Simple way to do it would be:
int n = 4; // Or whatever value - n has to be global so that the event handler can access it
private void btnDisplay_Click(object sender, EventArgs e)
{
TextBox[] textBoxes = new TextBox[n];
Label[] labels = new Label[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(textBoxes[i]);
this.Controls.Add(labels[i]);
}
}
The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.
To do it using a User Control simply do this.
Okay, first of all go and create a new user control and put a text box and label in it.
Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:
public string GetTextBoxValue()
{
return this.txtSomeTextBox.Text;
}
public string GetLabelValue()
{
return this.lblSomeLabel.Text;
}
public void SetTextBoxValue(string newText)
{
this.txtSomeTextBox.Text = newText;
}
public void SetLabelValue(string newText)
{
this.lblSomeLabel.Text = newText;
}
Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):
private void btnDisplay_Click(object sender, EventArgs e)
{
MyUserControl[] controls = new MyUserControl[n];
for (int i = 0; i < n; i++)
{
controls[i] = new MyUserControl();
controls[i].setTextBoxValue("some value to display in text");
controls[i].setLabelValue("some value to display in label");
// Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
}
// This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
for (int i = 0; i < n; i++)
{
this.Controls.Add(controls[i]);
}
}
Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:
public TextBox myTextBox;
public Label myLabel;
In the constructor of the user control do this:
myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;
Then in your program if you want to modify the text value of either just do this.
control[i].myTextBox.Text = "some random text"; // Same applies to myLabel
Hope it helped :)
Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel
and then just add controls to it
for ( int i = 0; i < COUNT; i++ ) {
Label lblTitle = new Label();
lblTitle.Text = i+"Your Text";
youlayOut.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
youlayOut.Controls.Add( txtValue, 2, i );
}
Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.
var n = 5;
for (int i = 0; i < n; i++)
{
//Create label
Label label = new Label();
label.Text = String.Format("Label {0}", i);
//Position label on screen
label.Left = 10;
label.Top = (i + 1) * 20;
//Create textbox
TextBox textBox = new TextBox();
//Position textbox on screen
textBox.Left = 120;
textBox.Top = (i + 1) * 20;
//Add controls to form
this.Controls.Add(label);
this.Controls.Add(textBox);
}
This will not only add them to the form but position them decently as well.
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}

Creating Dynamic ComboBox in C#

I'm new to Visual Studio 2010 C# and I'm creating an application where the user will select the number of textboxes will be shown in a form. For example, if the user will select "2" automatically there will be 2 boxes will be shown in the form.
This is the screenshots that I want to create.
I guess what you need to know is dynamic creation of controls.
To do what you want here you need to:
Create a control
Add control to form
Set control location, size and anything else you need
It would go something like this:
Texbox texbox = new Textbox();
Controls.Add(textbox);
textbox.Top = 20;
textbox.Left = 200;
textbox.Width = 200;
textbox.Name = "textbox1";
So that there's something left for you to do, you should repeat steps above in a loop, and calculate location of each textbox so that they're not stacked up.
comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
int y = 0;
while (i < int.Parse(comboBox1.SelectedItem.ToString()))
{
System.Windows.Forms.TextBox tt = new System.Windows.Forms.TextBox();
y = y + 30;
tt.Location = new System.Drawing.Point(0, y);
this.Controls.Add(tt);
i++;
}
}
Hope this helps

Create button during runtime in C#.net?

I know how to create button during runtime.
Button button1 = new Button();
button1.Location = new Point(20,10);
button1.Text = "Click Me";
// adding to groupBox1
groupBox1.Controls.Add(button1);
But the problem is i want to add multiple buttons like this..
for(int i = 1; i < 30; i++) {
Button button[i] = new Button();
// Button customization here...
...
groupBox1.Controls.Add(button[i]);
}
The code above is false code. How can I make this happen true in C#.net? i want to create multiple buttons with button name, button1, button2, button3, button4, .... button30;
You can't declare extra variables at execution time in C# - but you really don't want to anyway, as you wouldn't be able to access them dynamically afterwards. Just create an array:
// buttons would be declared as Button[] as a member variable
buttons = new Button[30];
for(int i = 0; i < buttons.Length; i++) {
buttons[i] = new Button();
// Button customization here...
...
groupBox1.Controls.Add(buttons[i]);
}
Alternatively, use a List<Button>, which will certainly be more convenient if you don't know how many buttons you need beforehand. (See the obligatory "arrays considered somewhat harmful" blog post.)
Of course, if you don't actually need to get at the buttons later, don't bother assigning them to anything visible outside the loop:
for(int i = 0; i < 30; i++) {
Button button = new Button();
// Button customization here...
...
groupBox1.Controls.Add(button);
}
You need to think about what information you need access to when... and how you want to access it. If you logically have a collection of buttons, you should use a collection type variable (like a list or an array).
Frankly I think it's one of the curses of the VS designers that you end up with horrible names such as "groupBox1" which carry no information beyond what's already in the type declaration, and encourage developers to think of collections of controls via individually-named variables. That's just me being grumpy though :)
Try this
for(int i = 1; i < 30; i++) {
Button button = new Button();
// Button customization here...
button.Name = "Button" + i.ToString();
groupBox1.Controls.Add(button);
}
You seem like you're almost on the right track:
// in form class
Button[] m_newButtons = new Button[30];
// in your trigger function
for(int i = 0; i < 30; ++i)
{
m_newButtons[i] = new Button();
// ...
groupBox1.Controls.Add(m_newButtons[i]);
}
If you try and do this more than once you may have to remove the old buttons from the control before adding the new ones.
buttons = new Button[30];
for(int i = 0; i < buttons.Length; i++) {
buttons[i] = new Button();
groupBox1.Controls.Add(buttons[i]);
}
this code will work but button will be added one over other so set location also
buttons = new Button[30];
for(int i = 0; i < buttons.Length; i++)
{
buttons[i] = new Button();
Point p=new Point(xvalue,yvalue);
buttons[i].Location = p;
groupBox1.Controls.Add(buttons[i]);
}
one thing you want to remember increment the x or y position by which you want to display it
Try this one out, I have just learned it myself:
public partial class Form1 : Form
{
Button[] btn = new Button[12];// <--------<<<Button Array
public Form1()
{
InitializeComponent();
}
private void Form1_Load (object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
btn[i] = new Button ( );
this.flowLayoutPanel1.Controls.Add(btn[i]);
}
}
// double click on the flow layoutPannel initiates this code
private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
}

Categories