How to change postition of a dynamicaly created text box? - c#

Stack overflow! I've been here multiple times and I've always managed to find an answer to my questions! But now I come forward with a problem that I can't find the solution for, Heres a bit of c# that generates a new TextBox when you press a button, How do I move the text box after its creation?
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int cLeft = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddNewTextBox();
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = cLeft * 25;
txt.Left = 100;
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
return txt;
}
}
}

To access the dynamic controls on a form, use the controls collection. For this example I added a new button on the form which moves all the text boxes on the form.
private void btnMove_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls) // all controls on form
{
if (c is Button) continue; // don't move buttons
if (c is System.Windows.Forms.TextBox) // move textboxes
c.Top += 1; // move down 1 pixel
c.Left += 1; // move right 1 pixel
}
}

Related

C# How do I link a number box to a scrollbar

I am new to C#. I need to link two number boxes to a single Vscrollbar. The scrollbar button is in the middle and set to zero, as the scroll button moves up or down the numbers change accordingly. I need a minus sign for below zero.
TIA.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
vScrollBar1.Value = vScrollBar1.Maximum / 2;
ChangeTextBoxValues(vScrollBar1.Maximum / 2, vScrollBar1.Value);
}
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
int avg = vScrollBar1.Maximum / 2;
ChangeTextBoxValues(avg, e.NewValue);
}
void ChangeTextBoxValues(int AvgValue, int NewValue)
{
textBox1.Text = (AvgValue - NewValue).ToString();
textBox2.Text = (NewValue - AvgValue).ToString();
}
}
Once you have the value you can do some maths with it to populate your textboxes.
private void vScrollBar1_ValueChanged(object sender, EventArgs e)
{
string value = vScrollBar1.Value.ToString();
}

Checking if a label I click, is a part of a pattern of labels

I am making a game about remembering a pattern of labels, that show up by them changing colors. The user then has to click the labels showed, in the correct order.
After the pattern has been randomly chosen, it goes into a list called the 'pattern'. My problem here is; how do I make it so that my label_Click event handler can be used to check if the correct label has been clicked for the entire list, in the correct order. Sorry that my code is clumsy and without comments, I have just started programming.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Spil
{
public partial class Form1 : Form
{
Random rnd = new Random();
Label[] labelArray;
int turn = 1;
int lives = 3;
List<Label> pattern = new List<Label>();
public Form1()
{
InitializeComponent();
labelArray = new Label[] { label1, label2, label3, label4, label5, label6, label7, label8, label9 };
}
private void DisplayOrder()
{
for (int i = 0; i < labelArray.Length; i++)
{
labelArray[i].BackColor = Color.Blue;
labelArray[i].Click += label_Click;
}
for (int i = -2; i < turn; i++)
{
int chosenNumber = rnd.Next(0, 9);
labelArray[chosenNumber].BackColor = Color.Green;
Thread.Sleep(1000);
labelArray[chosenNumber].BackColor = Color.Blue;
pattern.Add(labelArray[chosenNumber]);
}
}
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
}
private void Form1_Shown(object sender, EventArgs e)
{
System.Timers.Timer t = new System.Timers.Timer(100);
t.Elapsed += t_Elapsed;
t.Start();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
((System.Timers.Timer)sender).Stop();
DisplayOrder();
}
}
}
In order to keep track of matching user label clicks, you will need to keep track of the turn, so you know what index in pattern to look for when the user clicks a label.
So for the first click/turn, you can check if pattern[0] == clickedLabel. If it is the user was right and you can increment the index to 1, because that is the next label you expect to be clicked.
You can keep track of this by making some modifications to your code as shown below. Note: It only shows the modifications for keeping track of the user's tries, the rest of your original code remains untouched.
public partial class Form1 : Form
{
// A user is allowed a maximum of 3 guesses per label.
private const int MaxTries = 3;
// The number of guesses for the current label.
private int _triesOnCurrentLabel;
// The number of labels guessed correctly so far.
// This is also the index into the patterns list.
private int _numberGuessedRight;
// The game is over if the user guessed all labels
// or used more than the maximum number of tries on a label.
private bool _gameOver;
// ... other stuff
private void label_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
if (!_gameOver)
{
if (pattern[_numberGuessedRight] == clickedLabel)
{
// The user guessed right.
_triesOnCurrentLabel = 0; // reset, 3 tries for next label.
_numberGuessedRight++;
_gameOver = _numberGuessedRight == pattern.Count;
if (_gameOver)
{
// Show the user a message? "YOU WON"
}
}
else if (++_triesOnCurrentLabel >= MaxTries)
{
// User used up all tries on the current label.
_gameOver = true;
// Show the user a message? "Game over YOU LOSER"
}
}
}
// ... the rest
}

Button Click Frequency Array

I need to make a ListBox that displays how often a Button is clicked.
The user chooses how many buttons are available to click. Here is what I've tried:
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
for (int i = 0; i < freq_array[clicked]; i++)
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
freq_array uses the 'clicked' variable to add to the frequency that button has been clicked. Or, it's supposed to.
When I debug it, 'clicked' always comes out to 0. I want 'clicked' to equal the text value of the button that's clicked. When I try to run the program, I get an error saying "Input string was not in correct format."
Edit:
I was able to fix my program with help from you guys. I realized I didn't show enough of my code to be clear enough, and I apologize for that. I had to add some things and move things around and got it soon enough. Thank you all.
Here is the code just for those who may need help in the future:
public partial class Form1 : Form
{
int[] freq_array = new int[11];
int[] numList = new int[11];
int oBase = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
invisiblity();
}
private void invisiblity()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
ctrl.Visible = false;
}
}
private void btnSetBase_Click(object sender, EventArgs e)
{
Form2 frmDialog = new Form2();
frmDialog.ShowDialog(this);
if (frmDialog.DialogResult == DialogResult.OK)
{
oBase = frmDialog.Base;
//lblOutDigits.Text = oBase.ToString();
for (int i = 0; i < oBase; i++)
{
numList[i] = i;
}
}
ShowBaseButtons(oBase);
}
private void ShowBaseButtons(int last_digit)
{
invisiblity();
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
if (int.Parse(ctrl.Text) <= last_digit - 1)
ctrl.Visible = true;
}
}
private void btnN_Click(object sender, EventArgs e)
{
lblOutDigits.Text += ((Button)(sender)).Text;
int clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
}
private void btnShowFreq_Click(object sender, EventArgs e)
{
lstFrequencies.Items.Clear();
for (int i = 0; i < oBase; i++)
lstFrequencies.Items.Add(numList[i] + " \t\t\t" + freq_array[i]);
}
Your code should work as long as your Button Text is actually just a number. Since what you are trying to do is create an index, what I usually do is use the Tag Property of the control, set it to the Index I want in the designer and then cast that to an Int.
i.e.
if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
freq_array[clicked]++;
I believe what is happening is that you are not initializing your ListBox, This example Code does work using your initial method. Just create a new Form and paste it in and test.
public partial class Form1 : Form
{
ListBox lstFrequencies = new ListBox();
int[] freq_array = new int[10];
public Form1()
{
InitializeComponent();
Size = new Size(400, 400);
lstFrequencies.Location = new Point(150, 0);
lstFrequencies.Size = new Size(150, 200);
Controls.Add(lstFrequencies);
int top = 0;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Size = new Size(70, 30);
btn.Location = new Point(5, top);
Controls.Add(btn);
top += 35;
btn.Tag = i;
btn.Text = i.ToString();
btn.Click += new EventHandler(btn_Click);
lstFrequencies.Items.Add(i.ToString());
}
}
void btn_Click(object sender, EventArgs e)
{
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked]; //Cleaned up you do not need to iterate your list
// Using my example code
//if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
//{
// freq_array[clicked]++;
// lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
//}
}
}
Your code always comes out to 0 because you never assign last clicked value to button text. Try this code:
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
clicked = Convert.ToInt32(((Button)sender).Text);
lstFrequencies.Items.Add(((Button)sender).Name + " " + ++clicked);
button1.Text = clicked.ToString(); // you lose this line
}
EDIT: Counter from variable member
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
// if you want to display button name, change .Text to .Name
lstFrequencies.Items.Add(((Button)sender).Text + " " + ++clicked);
}

Value increment of textbox in C#.net

I have 2 textbox and 1 button textbox1,textbox2 and 1 increment button.Both textbox is initialize by 1.If i will click on textbox1 and then click on incr button the value belongs to textbox1 will be increase only.And whenever i will click on textbox2 and again i will click on incr button only textbox2 value will be increment.
How will i do this?
You didn't say whether you were in WinForms or in WPF, so I won't show any code.
Have a field TextBox activeTextBox in your class. In the GotFocus events of each textbox, set activeTextBox = this text box. In the button click, convert activeTextBox's text to an integer, add one, and convert back to string and set the text back.
Edit:
activeTextBox is a field you will need to set up, the designer won't make it for you. If you set the GotFocus event of textBox1 set activeTextBox = textBox1, and similar for textBox2, then activeTextBox will always have the 'current' text box. Then in the button's click event, you can do whatever you need to do on activeTextBox. You shouldn't need to access textBox1 or textBox2 from the button click handler at all.
This can be done on the client side using javascript. On focus of textbox1 update a hiddenfield value. similarly for the textbox2. then on button click, based on hidden f
Create a windows form application and paste this code on form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
TextBox textbox1 = new TextBox(), textbox2 = new TextBox();
Button button1 = new Button();
int FocusedTextBox = 0;
public Form1()
{
InitializeComponent();
this.Load += new System.EventHandler(this.Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
textbox1.Text = textbox2.Text = "1";
textbox1.Location = new Point(100, 100);
textbox2.Location = new Point(100, 140);
button1.Location = new Point(100, 180);
textbox1.Click += new EventHandler(textbox1_Click);
textbox2.Click += new EventHandler(textbox2_Click);
textbox1.ReadOnly = true;
textbox2.ReadOnly = true;
this.Controls.Add(textbox1);
this.Controls.Add(textbox2);
this.Controls.Add(button1);
}
void textbox2_Click(object sender, EventArgs e)
{
FocusedTextBox = 2;
}
void textbox1_Click(object sender, EventArgs e)
{
FocusedTextBox = 1;
}
void button1_Click(object sender, EventArgs e)
{
if (FocusedTextBox ==1)
textbox1.Text = (int.Parse(textbox1.Text) + 1).ToString();
else if (FocusedTextBox == 2)
textbox2.Text = (int.Parse(textbox2.Text) + 1).ToString();
}
}
}
private int pickedbox = 0
[...]
private void textBox1_Enter(...)
{
pickedbox = 0;
}
private void textBox2_Enter(...)
{
pickedbox = 1;
}
private void button1_Click(...)
{
switch(pickedbox)
{
case 0:
textBox1.Text = int.Parse(textBox1.Text)++;
break;
case 1:
textBox2.Text = int.Parse(textBox2.Text)++;
break;
}
}
if (textBox1.Focused)
{
textBox1.Text = (Convert.ToInt32(textBox1.Text) + 1) + "";
}
else if (textBox2.Focused)
{
textBox2.Text = (Convert.ToInt32(textBox2.Text) + 1) + "";
}
else if (textBox3.Focused)
{
textBox3.Text = (Convert.ToInt32(textBox3.Text) + 1) + "";
}
But ".Focused" is always returing False.
Why ?

Changing button background color on mouse-over event

I am developing a project in C# Windows applications (WinForms) in that I need to create a function to change the background color for all the buttons that are in the single form using button mouse-over event. How do I do that?
Changing all controls of type Button:
for (int i = 0; i < Controls.Count; i++)
if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
Example of hooks:
MouseEnter += new EventHandler(delegate(object sender, EventArgs e)
{
SetButtonColour(Color.Blue);
});
MouseLeave += new EventHandler(delegate(object sender, EventArgs e)
{
SetButtonColour(Color.Red);
});
public void SetButtonColour(Color colour)
{
for (int i = 0; i < Controls.Count; i++)
if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
}
Assuming you are just changing your own app, this isn't that difficult.
In the mouse over event, just loop over the Controls property of the form and for all items that are Button, change the back color. You will need to write a recursive function to find all of the buttons probably though, since a Panel (or GroupBox, etc) contains a Controls property for all of its controls.
Something like this:
public partial class Form1 : Form
{
Color defaultColor;
Color hoverColor = Color.Orange;
public Form1()
{
InitializeComponent();
defaultColor = button1.BackColor;
}
private void Form1_MouseHover(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
{
ctrl.BackColor = hoverColor;
}
}
}
private void Form1_MouseLeave(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
{
ctrl.BackColor = defaultColor;
}
}
}
}

Categories