I'm in a bit of a pickle at the moment, I've created a bit of code that creates 4 textboxes and adds them to a table layout at run time (code below) but I'm struggling with getting text from it, I tried getting the value from it as you would string s = TxtBox1.Text.ToString(); but it just gets a null reference, then I tried txt.Text.ToString();and this just gets the text from the last text box that was created.
private void button2_Click(object sender, EventArgs e)
{
int counter;
for (counter = 1; counter <= 4; counter++)
{
// Output counter every fifth iteration
if (counter % 1 == 0)
{
AddNewTextBox();
}
}
}
public void AddNewTextBox()
{
txt = new TextBox();
tableLayoutPanel1.Controls.Add(txt);
txt.Name = "TxtBox" + this.cLeft.ToString();
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
}
I've looked all over for the answers to this and as of yet found nothing if anybody has any ideas I would be grateful.
Thanks
this code picks textbox1 from tableLayoutPanel1, cast it from Control to TextBox and takes Text property:
string s = ((TextBox)tableLayoutPanel1.Controls["TxtBox1"]).Text;
if you need them all, then iterate over textboxes:
string[] t = new string[4];
for(int i=0; i<4; i++)
t[i] = ((TextBox)tableLayoutPanel1.Controls["TxtBox"+(i+1).ToString()]).Text;
You can try
var asTexts = tableLayoutPanel1.Controls
.OfType<TextBox>()
.Where(control => control.Name.StartsWith("TxtBox"))
.Select(control => control.Text);
That will enumerate the Text value for all child controls of tableLayoutPanel1 where their type is TextBox and their name starts with "TxtBox".
You can optionally relax the filters removing the OfType line (that excludes any non TextBox control) or the Where line (that allow only the control which name matches your example).
Ensure to have
Using System.Linq;
at the beginning of the file.
Regards,
Daniele.
public void AddNewTextBox()
{
txt = new TextBox();
tableLayoutPanel1.Controls.Add(txt);
txt.Name = "TxtBox" + this.cLeft.ToString();
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
txt.KeyPress += txt_KeyPress;
}
private void txt_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//the sender is now the textbox, so that you can access it
System.Windows.Forms.TextBox textbox = sender as System.Windows.Forms.TextBox;
var textOfTextBox = textbox.Text;
doSomethingWithTextFromTextBox(textOfTextBox);
}
Related
I am trying to get a clickable file path using asp.net c# visual studios web form, meaning to say that it is like windows file explorer, allowing the person to navigate through the different levels of folders etc, can anyone provide any links to help get me started? [1]: https://i.stack.imgur.com/WyyLq.png
You could try to get the path string and divide it in multiple pieces. Then store them in multiple textboxes, labels, buttons or whatever you want. My form looks like this: Picture Form
Secondly, you will have to update those (in my case) textboxes to save the path. See my code and decide what you want to use, and if you have to modify it.
private void changePath()
{
String path = webBrowser1.Url.AbsolutePath;
if (path.Contains(#"/")) { path = path.Replace(#"/", #"\"); }
string[] directories = path.Split(Path.DirectorySeparatorChar);
int count = directories.Count();
if (count <= 6)
{
textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; textBox6.Text = "";
for (int i = 0; i < count; i++)
{
String txt = "textBox" + (i + 1);
TextBox tbx = this.Controls.Find(txt, true).FirstOrDefault() as TextBox;
tbx.Text = directories[i];
}
}
else
{
int p = count / 6;
int z = count - (p * 6);
for (int i = 0; i < count; i++)
{
int g = i - 1;
String txt = "textBox" + (i + 1);
TextBox tbx = this.Controls.Find(txt, true).FirstOrDefault() as TextBox;
tbx.Text = directories[z];
z++;
if (i == 5)
{
break;
}
}
}
}
Second step is to make click functions on the (in my case) textboxes. Here is one sample of how you can do this. See for yourself what you can do.
private void textBox5_Click(object sender, EventArgs e)
{
if(!textBox5.Text.Equals(String.Empty))
{
String p = webBrowser1.Url.AbsolutePath;
if(!textBox6.Text.Equals(String.Empty))
{
webBrowser1.Url = new Uri(p.Replace(#"/" + textBox6.Text, ""));
}
}
}
This code will remove the last piece, leaving you with a new path. Example:
Before: C:\Users\USERNAME\Desktop\C#
After:
After: C:\Users\USERNAME\Desktop
Again, you have to look what works for you. There are multiple ways to resolve your issue.
Good Luck!
Twan.
I am just looking to know this to try and clean up my code, and also for future reference.
I have a number of textBoxes.
tbPart1.Clear();
tbPart2.Clear();
tbPart3.Clear();
tbPart4.Clear();
tbPart5.Clear();
tbPart6.Clear();
tbPart7.Clear();
Is there any way I could use a loop to replace the numbers?
I tried this, but have no idea how i could run the string.
for (int i = 1; i == 7; i++)
{
string p = "tbPart" + i.ToString() + ".Clear";
}
Inside of the form's code (i.e. in a button click event handler), you can enumerate through all of the TextBox controls on the form and perform a specific action on them:
this.Controls.OfType<TextBox>().ToList().ForEach(x => x.Clear());
If you need to only clear some of the TextBox controls, you can provide a sort of filter like so:
this.Controls.OfType<TextBox>()
// Add a condition to clear only some of the text boxes - i.e. those named "tbPart..."
.Where(x=>x.Name.StartsWith("tbPart"))
.ToList().ForEach(x => x.Clear());
No, you cannot do it that way. But you can define an array or list where you put the controls and then clear them. For example:
List<TextBox> textboxes = new List<TextBox>();
textboxes.Add(tbPart1);
textboxes.Add(tbPart2);
textboxes.Add(tbPart3);
...
Then when you want to clear them
foreach (var tb in textboxes)
tb.Clear();
TextBox[] boxes = new [] {
tbPart1,
tbPart2,
tbPart3,
tbPart4,
tbPart5,
tbPart6,
tbPart7
};
for (int i = 0; i < boxes.Length; i++)
{
boxes[i].Clear();
}
i think you should use an array of textbox then you can do a loop depends the count of numbers of textboxes.
foreach(Control ctrl in this.Controls)
{
if(ctrl.GetType() == typeof(TextBox))
{
ctrl.Text = String.Empty;
}
}
Answer number one by using Control name inside panel1
private void button2_Click(object sender, EventArgs e)
{
string currentCtrlName;
for (int i = 0; i < panel1.Controls.Count; i++)
{
currentCtrlName = "textBox" + (i+1).ToString();
panel1.Controls[currentCtrlName].Text = "";
}
}
==================
Answer number one by using Control index as a child inside panel1
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < panel1.Controls.Count; i++)
{
panel1.Controls[i].Text = "";
}
}
==================
My code:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text = infos;
}
timer4.Stop();
}
I want to insert all of 10 src values in RichTextBox, while my code do it only once.
You can use AppendText
Replace
richTextBox1.Text = infos;
with
richTextBox1.AppendText(infos);
OR
richTextBox1.Text += infos + Environment.NewLine;
This line is wrong.
richTextBox1.Text = infos;
This is right.
richTextBox1.AppendText= infos;
What your code is doing is setting the text to equal each infos, 10 times over.
So I'm guessing your output would be the last infos variable? What you might want to do instead is this:
private void timer4_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 10; a++)
{
var infos = webBrowser1.Document.GetElementsByTagName("img")[a].GetAttribute("src");
richTextBox1.Text += infos; // the "+=" will add each infos to the textbox
}
timer4.Stop();
}
As you can see, if you use the += instead of just =, it will add each iteration to the whole, instead of just overriding the whole value each time.
I want to auto format a text entered in a textbox like so:
If a user enters 2 characters, like 38, it automatically adds a space. so, if I type 384052
The end result will be: 38 30 52.
I tried doing that, but it's ofr some reason right to left and it's all screwed up.. what I'm doing wrong?
static int Count = 0;
private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
Count++;
if (Count % 2 == 0)
{
packetTextBox.Text += " ";
}
}
Thanks!
It's much nicer if you just let the user type and then modify the contents when the user leaves the TextBox.
You can do that by reacting not to the KeyPress event, but to the TextChanged event.
private void packetTextBox_TextChanged(object sender, EventArgs e)
{
string oldValue = (sender as TextBox).Text.Trim();
string newValue = "";
// IF there are more than 2 characters in oldValue:
// Move 2 chars from oldValue to newValue, and add a space to newValue
// Remove the first 2 chars from oldValue
// ELSE
// Just append oldValue to newValue
// Make oldValue empty
// REPEAT as long as oldValue is not empty
(sender as TextBox).Text = newValue;
}
On TextChanged event:
int space = 0;
string finalString ="";
for (i = 0; i < txtbox.lenght; i++)
{
finalString = finalString + string[i];
space++;
if (space = 3 )
{
finalString = finalString + " ";
space = 0;
}
}
I used
int amount;
private void textBox1_TextChanged(object sender, EventArgs e)
{
amount++;
if (amount == 2)
{
textBox1.Text += " ";
textBox1.Select(textBox1.Text.Length, 0);
amount = 0;
}
}
Try this..
on TextChanged event
textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0");
textBoxX3.SelectionStart = textBoxX3.Text.Length + 1;
Was trying out a simple FB API app to retrieve status.
So what i am intending to do is to perform a word check with my dictionary.
I have a database which stores emotive data on the feeling % and the genre of the feeling.
If the status contains the emotive word, i wish to perform a word analysis.
For instance: "I am feeling sad and angry"
So what i want it to display is like...
"Username"
was feeling
50% angry
and 25% sad.
*% is calculated by random function.
However, i think its impossible for me to keep creating labels. What if my status has > 5 emotions? Is it possible to create automatic labels which would display the output?
Below is my code:
private void EmotionAnalysis_Load(object sender, EventArgs e)
{
label1.Text = tpc.loadInfo(currentId)["target_name"].ToString();
//List<DataRow> result = dict.AngerPercent(fbStatus);
CalculateAndDisplayAnalysis("Angry", topPercentLabel, topFeelingLabel);
CalculateAndDisplayAnalysis("Caring", bottomPercentLabel, bottomFeelingLabel);
//var item = new ListViewItem(new[] { "", String.Format("{0}%", percent.ToString()), result[0]["Genre"].ToString() });
//listViewEmotion.Items.Add(item);
}
private void CalculateAndDisplayAnalysis(string genre, Label percentLabel, Label feelingLabel)
{
List<DataRow> result = dict.GenrePercent(fbStatus, genre);
var rnd = new Random();
int total = 0;
for (int i = 0; i < result.Count; i++)
{
total += rnd.Next(Convert.ToInt32(result[i]["Min_Percentage"]), Convert.ToInt32(result[i]["Max_Percentage"]));
}
if (result.Count != 0)
{
int percent = total / result.Count;
percentLabel.Text = String.Format("{0}%", percent.ToString());
feelingLabel.Text = result[0]["Genre"].ToString();
}
}
You can create as many labels as you want. you just need to set the position of the label and add it to the forms Controls enumeration:
Label lbl = new Label();
lbl.Text = "MyText";
lbl.Location = new Position(xPos, yPos);
this.Controls.Add(lbl);
You will have to keep track of the new position which is in this case determined by xPos and yPos