I am trying to do something like this : I have a textbox in which I put a number.
When I press enter I save this number in my variable id.
Then I want to create the exact same number of textboxes as my id variable.
It doesn't work because you can't set unknown variable in an array but how could I modify this code to get the result I want?
private void tbNbCat_KeyDown(object sender, KeyEventArgs e)
{
int id=0;
if (e.KeyCode == Keys.Return){
id = int.Parse(tbNbCat.Text);
MessageBox.Show(id.ToString());
createTxtTeamNames(id);
}
}
public void createTxtTeamNames(int id)
{
TextBox[] txtTeamNames = new TextBox[id];
for (int u = 0; u < id; u++)
{
txtTeamNames[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
Thanks.
Change
TextBox[] txtTeamNames = new TextBox[id];
To
List<TextBox> txtTeamNames = new List<TextBox>();
Why are you using the array in the first place?
public void createTxtTeamNames(int id)
{
for (int i = 0; i < id; ++i)
{
TextBox txt = new TextBox();
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
}
}
Related
I am taking input from 5 textboxes and sorting the values inserted into the text boxes by putting them into labels and moving the labels around till the values in them are sorted.
I have so far put them into labels, but I don't know how to move he labels on button click and let the labels move to get sorted.
This is one way of simulating the algorithm of insertion sort.
my code so far for button click :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
myLabel[0].Text = textBox1.Text;
myLabel[1].Text = textBox5.Text;
myLabel[2].Text = textBox4.Text;
myLabel[3].Text = textBox3.Text;
myLabel[4].Text = textBox2.Text;
}
public partial class Form1 : Form
{
Label[] myLabel=new Label[5];
int a = 30; //x coordinates of first label in label1 array
int b = 125; //y coordinates of first label in label1 array
int c = 0;
int k = 0;
int n = 0;
int j = 1;
int i;
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Selection Sort");
comboBox1.Items.Add("Insertion Sort");
}
you need to sort value of textbox and then put value in labels. Something like this :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>(textBox1.Text, textBox1.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox2.Text, textBox2.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox3.Text, textBox3.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox4.Text, textBox4.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox5.Text, textBox5.Text.Value));
list.Sort(Compare2);
int increment = 0;
foreach(var item in list)
{
myLabel[increment].Text=item.Value;
increment++;
}
}
static int Compare2(KeyValuePair<string, string> a, KeyValuePair<string, string> b)
{
return a.Value.CompareTo(b.Value);
}
I have been trying to create a chess strategy application. I seem to be having issues with trying to get the label1 control to populate during run time. I am actually pretty new to the idea of dynamically creating events like 'mouse enter, mouse leave' How do I get the label to show the coordinates in the mouse enter event
int currentXposition, currentYposition;
const string positionLabel = "Current Position: ";
private void Test_Load(object sender, EventArgs a)
{
var temp=Color.Transparent; //Used to store the old color name of the panels before mouse events
var colorName = Color.Red; //Color used to highlight panel when mouse over
int numBlocks = 8; //Used to hold the number of blocks per row
int blockSize=70;
//Initialize new array of Panels new
string[,] Position = new string[8, 8];
Panel[,] chessBoardPanels = new Panel[numBlocks, numBlocks];
string Alphabet = "A,B,C,D,E,F,G,H";
string Numbers ="1,2,3,4,5,6,7,8";
string[] alphaStrings = Numbers.Split(',');
string[] numStrings=Numbers.Split(',');
// b = sub[0];
int FirstValue, SecondValue;
//Store Position Values
for (int firstValue = 0; firstValue < 8; ++firstValue)
{
FirstValue = Alphabet[firstValue];
for (int SecValue = 0; SecValue < 8; ++SecValue)
{
SecondValue = Numbers[SecValue];
Position[firstValue, SecValue] = alphaStrings[firstValue] + numStrings[SecValue];
}
}
//Loop to create panels
for (int iRow = 0; iRow < numBlocks; iRow++)
for (int iColumn = 0; iColumn < numBlocks; iColumn++)
{
Panel p = new Panel();
//set size
p.Size = new Size(blockSize, blockSize);
//set back colour
p.BackColor = (iRow + (iColumn % 2)) % 2 == 0 ? Color.Black : Color.White;
//set location
p.Location = new Point(blockSize *iRow+15, blockSize * iColumn+15);
chessBoardPanels[iRow, iColumn] = p;
chessBoardPanels[iRow,iColumn].MouseEnter += (s,e) =>
{
currentXposition = iRow;
currentYposition = iColumn;
var oldColor = (s as Panel).BackColor;
(s as Panel).BackColor = colorName;
temp = oldColor;
label1.Text = Position[iRow, iColumn];
};
chessBoardPanels[iRow, iColumn].MouseLeave += (s, e) =>
{
(s as Panel).BackColor = temp;
};
groupBox1.Controls.Add(p);
}
}
Try this.. It was not populating because of a out of range.. iRow always = 8...
Add this class to your project.
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number); }
}
public ChessSquare()
{
}
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
Replace the FormLoad method with this:
int blockSize = 20;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65+i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.AliceBlue : Color.White;
Panel p = new Panel()
{ Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j+15),
};
p.MouseEnter+=new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
And add those two methods to your code:
void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel) sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
I there are several ways of doing it... This one is pretty straight forward.
I have a Button that creates a list of TextBoxes Dynamically and I also have a Button that submits the information. However I don't know how to access the values of the Textboxes. Below is the code:
if (IsPostBack)
{
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
int Count = int.Parse(string.Format("{0}", ViewState["count"]));
var lstTextBox = new List<TextBox>();
for (int i = 0; i < Counter; i++)
{
TextBox txtbx = new TextBox();
txtbx.ID = string.Format("txtbx{0}", i);
// txtbx.AutoPostBack = true;
lstTextBox.Add(txtbx);
//txtbx.Text = "initial value";
}
Session["lstTextBox"] = lstTextBox;
}
protected void Button1_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)//Calls to createbox
CreateTextBox(i);
//Label1.Text = Counter.ToString();
if (Counter == 4)
{
Button1.Visible = false;
}
}
private int Counter
{
get { return Convert.ToInt32(ViewState["count"] ?? "0"); } //Fields button counter
set { ViewState["count"] = value; }
}
private void CreateTextBox(int j) //Creates the fields / cells
{
var box = new TextBox();
box.ID = "Textbox" + j;
box.Text = "Textbox" + j;
var c = new TableCell();
c.Controls.Add(box);
r.Cells.Add(c);
table1.Rows.Add(r);
}
How would like to have Button2 grab the values.
Thank you in advance!!
do it like this
foreach(Control c in YourControlHolder.Controls)
{
if(c is TextBox)
{
//your code here.
}
}
I have a method that creates textboxes depending on the number of parameters values that the user has to enter.And its working fine. The problem is that when the user clicks Ok i want to take the value that the user entered in these textboxes and replace them in a string. When am searching these textboxes to get the text value from them am not finding them. How do i get these values to continue my project? the code is:
protected void btnPreview_Click(object sender, EventArgs e)
{
lbHeader.Text = "Template Designer";
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = false;
divFloating.Visible = true;
if (txtQuery.Text.Contains("WHERE") || txtQuery.Text.Contains("where")||txtQuery.Text.Contains("Where"))
{
string[] splitter=new string[10];
splitter[0]="Where";
splitter[1]="WHERE";
splitter[2]="where";
splitter[3]="AND";
splitter[4] = "and";
splitter[5] = "And";
string[] condition=txtQuery.Text.Split(splitter, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] Condition1 =null;
Label[] newLabel = new Label[10];
TextBox[] txtBox = new TextBox[10];
for (int i = 0; i < numberOfParameters; i++)
{
string lbValue="lbValue";
string lbID=lbValue+i;
string txtValue = "txtValue";
string txtID = txtValue + i;
HtmlGenericControl genericControl = new HtmlGenericControl("br/");
Condition1 = condition[i + 1].Split('[', ']');
newLabel[i] = new Label();
txtBox[i] = new TextBox();
newLabel[i].ID=lbID;
newLabel[i].Text = Condition1[1];
txtBox[i].ID = txtID;
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
txtBox[i].EnableViewState = true;
}
}
}
private bool ControlExistence(string lbID)
{
try
{
td2.FindControl(lbID);
return true;
}
catch(Exception ex)
{
return false;
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
// GetTextBoxValues();
string[] splitter1 = new string[10];
splitter1[0] = "Where";
splitter1[1] = "WHERE";
splitter1[2] = "where";
splitter1[3] = "AND";
splitter1[4] = "and";
splitter1[5] = "And";
string[] condition = txtQuery.Text.Split(splitter1, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] splitter = new string[4];
splitter[0] = "[";
splitter[1] = "]";
splitter[2] = "'";
string[] queryBoxValue = txtQuery.Text.Split(splitter,StringSplitOptions.RemoveEmptyEntries);
StringBuilder query = new StringBuilder();
TextBox txtBox = new TextBox();
for (int i = 0; i < queryBoxValue.Length; i++)
{
if (!queryBoxValue[i].Contains("?"))
{
query.Append(queryBoxValue[i]);
query.Append(" ");
}
else
{
for (int counter1 = 0; counter1 < numberOfParameters; counter1++)
{
string txtValue = "txtValue";
string txtID = txtValue + counter1;
if (ControlExistence(txtID))
{
TextBox box = (TextBox)td2.FindControl(txtID);
string b = box.Text;
//txtBox.ID = txtID;
}
txtBox.Text = "'" + txtBox.Text + "'";
queryBoxValue[i] = queryBoxValue[i].Replace(queryBoxValue[i], txtBox.Text);
query.Append(queryBoxValue[i]);
}
}
}
string fireQuery = query.ToString();
adp = new SqlDataAdapter(fireQuery, conn);
tab = new DataTable();
adp.Fill(tab);
if (tab.Rows.Count > 0)
{
string[] tempString = txtTemplate.Text.Split(' ');
for (int j = 0; j < tempString.Length; j++)
{
if (tempString[j].StartsWith("["))
{
txtPreview.Text = txtTemplate.Text.Replace(tempString[j], tab.Rows[0][0].ToString());
}
}
}
divFloating.Visible = false;
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = true;
}
Please help. This has become a blocker for me.
Have a list of the added controls and use it when needed.
for (int i = 0; i < numberOfParameters; i++)
{
// ...
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
addedTextBoxes.Add(txtBox[i]);
// ...
}
And then from another part of your code:
var values = addedTextBoxes.Select(tb => tb.Text).ToList();
foreach (var txtBox in addedTextBoxes)
{
// ...
}
etc...
This is my code.
But all my textboxes's value is just null.
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[teams];
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
i++;
}
}
Thanks for the help.
The array creation call just initializes the elements to null. You need to individually create them.
TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
var txt = new TextBox();
txtTeamNames[i] = txt;
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
}
Note: As several people have pointed out in order for this code to be meaningful you will need to add each TextBox to a parent Control. eg this.Controls.Add(txt).
You need to initialize your textbox at the start of the loop.
You also need to use a for loop instead of a foreach.
You need to new up your TextBoxes:
for (int i = 0; i < teams; i++)
{
txtTeamNames[i] = new TextBox();
...
}
You are doing it wrong, you have to add textbox instances to the array, and then add it to the form. This is how you should do it.
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[10];
for (int u = 0; u < txtTeamNames.Count(); u++)
{
txtTeamNames[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
private void button2_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = abc;
tb.Text = "" + i;
Point p = new Point(20 + i, 30 * i);
tb.Location = p;
this.Controls.Add(tb);
i++;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (TextBox item in this.Controls.OfType<TextBox>())
{
MessageBox.Show(item.Name + ": " + item.Text + "\\n");
}
}