I created, dynamically, a number of textBoxes. The user will write input in those textBoxes and then press a button ("SAVE").
I want to save the info from those textBoxes in an array(or string). Is it possible to implement something like this: for(i = 0; i < the_number_of_textBoxes; i++) MY_ARRAY_or_MY_STRING += textBox[i].Text; //I know this isn't correct
I'm sure there should be something similar to my "way of thinking", but I can't find it.
If I would always have the same number of texboxes, lets say 2, I could implement it like this: MY_ARRAY_or_MY_STRING = textBox1.Text + textBox2.Text;, but my textBoxes are dynamicaly generated.
Here is the code I use (although I don't think it will be of need), my program has 2 Forms (Form1 is noted as frm1) - It has nothing to do with my question, but maybe it helps, idk. If you need more info about what the program does, ask away, I wont write it here, because it may be useless info.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Add MySql Library
using MySql.Data.MySqlClient;
namespace Proiect
{
public partial class Form2 : Form
{
public Form1 frm1;
public int numar_textBox = 5;
public int numar_eticheta = 5;
public int numar_groupBox = 0;
public int LastTextBoxLeft = 15;
public int LastEtichetaLeft = 15;
public int LastGroupBoxLeft = 3;
public Form2()
{
InitializeComponent();
frm1 = new Form1();
}
private void Form2_Load(object sender, EventArgs e)
{
int i;
for (i = 0; i < frm1.get_nr_coloane(); i++)
AddNewGroupBox();
}
private void Form2_Click(object sender, EventArgs e)
{
Deselect.Focus(); //Deseleceaza orice element, mutand focusul pe un label fara text
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
/*
public int verifica_spatii(TextBox New_text_box)
{
int i, k=0;
if (New_text_box.Text == "") return 1;
else
{
for (i = 0; i < New_text_box.TextLength; i++)
if (New_text_box.Text[i] != ' ')
{
return 1;
}
return 0; // are numai spatii
}
}
*/
public void On_click()
{
}
public event EventHandler Click_event;
public System.Windows.Forms.GroupBox AddNewGroupBox()
{
EventHandler handler = Click_event;
System.Windows.Forms.GroupBox grp = new System.Windows.Forms.GroupBox();
this.Controls.Add(grp);
grp.Width = 133;
grp.Height = 50;
grp.Top = 10;
grp.Left = LastGroupBoxLeft;
LastGroupBoxLeft += grp.Width;
grp.Text = frm1.get_nume_coloane()[numar_groupBox];
numar_groupBox += 1;
TextBox txt = new TextBox();
txt.Top = 20;
txt.Left = 10;
numar_textBox = numar_textBox + 1;
grp.Controls.Add(txt);
txt.Leave += textBoxGeneral_LostFocus;
/////New_text_box.Click += handler(this,);
return grp;
}
private void textBoxGeneral_LostFocus(object sender, EventArgs e)
{
//ToolStripItem item = (ToolStripItem)sender;
// MessageBox.Show(item.Text);
}
private void button1_Click(object sender, EventArgs e)
{
string valorile_de_adaugat="";
int i;
for(i=0;i<numar_groupBox-1;i++)
valorile_de_adaugat+=textBox[i]
//MySqlCommand Salveaza_in_baza_de_date = new MySqlCommand("INSERT INTO " + frm1.get_nume_tabel_selectat() + " ("+ frm1.get_unirea_coloanelor + ") VALUES(22056, 15, 2000, 2004));
}
/*
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
*/
}
}
Thank you for your time,
Vlad
Related
I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown
I need a bit of help with this code I am writing to produce and test the different types of loop conditions It has several lines that have errors that are causing the compiler to not build the solution. Don't know if it is the specific library that I am not calling right or if I am missing something in particular with the code. I created a particular folder that stores the correct images that I want the loop to use for the pictureBox, but it still has errors where it states the variable is out of text; it now states that System.OutOfMemoryException: 'Out of memory.'
:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PictureBox
{
public partial class Form1 : Form
{
int num1, num2;
Image[] Bully = new Image[10];
int randomNum;
Image dog= Image.FromFile(#"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\Form1.cs");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
pictureBox1.Image = Bully[i];
i++;
Bully[0] = Image.FromFile("Bully1.jpeg");
Bully[1] = Image.FromFile("Bully2.jpeg");
Bully[2] = Image.FromFile("Bully3.jpeg");
Bully[3] = Image.FromFile("Bully4.jpeg");
Bully[4] = Image.FromFile("Bully5.jpeg");
Bully[5] = Image.FromFile("Bully6.jpeg");
if (int.TryParse(textBox1.Text, out num1))
{
if (int.TryParse(textBox2.Text, out num2))
{
while ( i < num2)
{
MessageBox.Show("i=" + i);
pictureBox1.Image = Bully[i];
i++;
}
}
}
}
private void Form2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
Bully[0] = Image.FromFile("Bully1.jpeg");
Bully[1] = Image.FromFile("Bully2.jpeg");
Bully[2] = Image.FromFile("Bully3.jpeg");
Bully[3] = Image.FromFile("Bully4.jpeg");
Bully[4] = Image.FromFile("Bully5.jpeg");
Bully[5] = Image.FromFile("Bully6.jpeg");
if (int.TryParse(textBox2.Text, out num2))
{
for (int i = num1; i <= num2; i++)
{
MessageBox.Show("Bully Number= " + i);
pictureBox1.Image = Bully[i];
}
}
}
private double Average(int num1, int num2)
{
double result = (num1 + num2) / 2;
return result;
}
private void avg1_Click(object sender, EventArgs e)
{
double res = Average(1, 100);
textBox4.Text = res.ToString();
}
private void button4_Click(object sender, EventArgs e, string textLine)
{
StreamReader fileIn = new StreamReader(#"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\Form1.cs");
// This Reads The First Line Of Text
// Read The Next Line Of Text
textLine = fileIn.ReadLine();
MessageBox.Show("From File ..." + textLine);
fileIn.Close();
}
private void button5_Click(object sender, EventArgs e)
{
StreamWriter FileOut = new StreamWriter(#"C:\Users\Empiric Library\source\repos\PictureBox\PictureBox\Form1.cs");
string str = "BullyProof";
int number = 16;
FileOut.WriteLine(str);
FileOut.WriteLine(number);
// To Write In Output Stream
FileOut.Flush();
// To Close The Stream
FileOut.Close();
}
private void button3_Click(object sender, EventArgs e)
{
Random random = new Random();
randomNum = random.Next(1, 42);
textBox3.Text = randomNum.ToString();
}
}
}
I got a list of 10 items.
when a user puts in a value in "listText" its comparing to the first item in displayArraysString.
Lets say its not the first item in the displayArraysString list, then it doesnt do anything (Because I dont have a loop)
How do I create a loop that will check through my list and display the messagebox once it finds it. I tried with a try catch loop but that didnt work for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Arrays
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] numbers = new int[5];
List<int> numbersList = new List<int> ();
string text = System.IO.File.ReadAllText(#"C:Directory\list.txt");
private void Form1_Load(object sender, EventArgs e)
{
//numbers[0] = 12;
//numbers[1] = 10;
//numbers[2] = 25;
//numbers[3] = 10;
//numbers[4] = 15;
//numbersList.Add(23);
//numbersList.Add(32);
//numbersList.Add(35);
}
//Array Print
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < numbers.Length; i++)
displayArrays.Text += numbers[i].ToString() + ", ";
}
//List Print
private void button2_Click(object sender, EventArgs e)
{
for (int o = 0; o < text.Length; o++)
{
displayArraysString.Text += text[o].ToString();
if (listText.Text == displayArraysString.Text)
{
MessageBox.Show("Found a match!");
}
else
{
//Something.
}
}
}
}
}
You are trying something wrong here,
as the file you have read from the path in string , it will match a single character for listText, so there will be never a match,
I did it with string array, to convert the text data into string array of every words in it. If you search now than match will be found for listText.
try this code:
namespace Arrays
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] numbers = new int[5];
List<int> numbersList = new List<int> ();
string text = System.IO.File.ReadAllText.Text(#"C:\Directory\list.txt");
string[] displayStringArrays = null;
private void Form1_Load(object sender, EventArgs e)
{
//numbers[0] = 12;
//numbers[1] = 10;
//numbers[2] = 25;
//numbers[3] = 10;
//numbers[4] = 15;
//numbersList.Add(23);
//numbersList.Add(32);
//numbersList.Add(35);
}
//Array Print
private void button1_Click(object sender, EventArgs e)
{
displayArrays.Text = listText.Text;
}
//List Print
private void button2_Click(object sender, EventArgs e)
{
displayStringArrays = text.Split('\n').ToArray();
foreach (var item in displayStringArrays)
{
displayArraysString.Text += item;
if (listText.Text == item.Substring(0, item.Length - 1) || listText.Text == item)
{
MessageBox.Show("Found a match!");
}
else
{
//Something.
}
}
}
}
}
replace this code with your code. I checked this it is working fine now.
Hey guys I need some help creating a counter for user input based on how much time they enter a guess to guess a random number from 1 - 100. So far this is what I have but it only output 1 count and does not count the next input. Can you please tell me what I am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
}
private void btnReset_Click(object sender, EventArgs e)
{
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
Random r = new Random();
int target = r.Next(0, 101);
int userGuess = int.Parse(txtGuess.Text);
int guessCount = 0;
if (userGuess == target)
{
guessCount++;
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = "You guess the right number " + "it took you: " + guessCount.ToString() + " guesses";
}
else if (userGuess < target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Yellow;
}
else if (userGuess > target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Red;
}
lblCount.Text = "You made: " + guessCount.ToString() + " Guesses";
}
}
}
The issue with your code is that you are setting the guess counter to zero every time btnCheck is clicked. You need to make sure it is reset only once per guess session.
So this means that you need to move guessCount out as a class-level variable and make sure that you only reset it at the first run of the form and whenever btnReset is clicked.
Here's how I would refactor your code to achieve this:
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
ResetData();
}
private void btnReset_Click(object sender, EventArgs e)
{
ResetData();
}
private Random r = new Random();
private int guessCount;
private int target;
private void ResetData()
{
guessCount = 0;
target = r.Next(0, 101);
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
int userGuess = int.Parse(txtGuess.Text);
guessCount++;
if (userGuess == target)
{
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = String.Format(
"You guessed the right number it took you {0} guesses",
guessCount);
}
else
{
this.BackColor = userGuess < target
? System.Drawing.Color.Yellow
: System.Drawing.Color.Red;
}
lblCount.Text = String.Format(
"You made {0} Guesses",
guessCount);
}
}
You'll also notice that you were resetting the target each time btnCheck was clicked. That too needed to be moved to a class-level variable.
It's also a good habit to get in to making instances of Random a class-level variable too as there are circumstances where you can end up with less-than random numbers if you don't.
You'll notice that I moved all of the reset code into a new ResetData method that can get called both when the form loads and when btnReset is clicked.
It can't be so obvious. Why are you setting int guessCount = 0 in btnCheck_Click? Why don't you keep a global counter?
To make it global, take out int guessCount = 0; from the btnCheck_Click function and put it at the top where it appears like:
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
int guessCount = 0;
That way guessCount won't be continually reset to zero and then incremented each time you press the btnCheck button.
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 Mod
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int c = 0;
private void button1_Click(object sender, EventArgs e)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic" + c++;
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * c));
txtRun.Size = new System.Drawing.Size(200,15);
this.Controls.Add(txtRun);
}
private void button2_Click(object sender, EventArgs e)
{
List<string>tilelocation = List<string>();
tilelocation.Add(); //What goes in this method's arguments?
}
}
}
Here is my code. Button1 creates a theoretically infinite # of textboxes, but I wish to add the text in these dynamically generated textboxes to a list. How can this be done?
[EDIT]
And how can I display them all in a messagebox, each on separate lines?
You need to keep a reference to the control.
The other secret is that you have to keep it in the ViewState so it's available between post backs.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
int c = 0;
private List<TextBox _lstTextBoxList;
public List<TextBox> lstTextBoxList {
get {
if(_lstTextBoxList == null) {
_lstTextBoxList = ViewState["lstTextBoxList"] as List<TextBox>;
}
return _lstTextBoxList;
}
set { ViewState["lstTextBoxList"] = _lstTextBoxList = value; }
}
private void button1_Click(object sender, EventArgs e) {
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic" + c++;
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * c));
txtRun.Size = new System.Drawing.Size(200,15);
this.Controls.Add(txtRun);
lstTextBoxList.Add(txtRun);
}
private void button2_Click(object sender, EventArgs e) {
// Not sure of your goal here:
List<string> tilelocation = List<string>();
tilelocation.Add(lstTextBoxList[lstTextBoxList.Count - 1]);
// I would assume you wanted this:
List<string> strValues = lstTextBoxList.Select<TextBox,string>(t => t.Text).ToList();
}
}
but I wish to add the text in these dynamically generated textboxes to
a list. How can this be done?
You should use new List<string> like:
private void button2_Click(object sender, EventArgs e)
{
List<string> tilelocation = new List<string>();
foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(r=> r.Name.StartsWith("txtDynamic"))
titlelocation.Add(tb.Text);
//if you want a string out of it.
string str = string.Join(",", titlelocation);
MessageBox.Show(str);
}
EDIT: For each text on new line use:
string str = string.Join(Environment.NewLine, titlelocation);
MessageBox.Show(str);
I don't know why you want to use a seperate button2 click event to add the text. Why don't you use a global variable tilelocation, and add the text to this list in the button1_click event? Something like:
txtRun.Text=Your Text;
tilelocation.add(Your Text);
If you want to display them in a message box, then add codes:
string str="";
foreach(text in tilelocation)
{
str+=text;
}
MessageBox.Show(str);