How to concatenate the contents of variable in the name of label and others variables?
//labels: lbl_01_temp, lbl_02_temp, lbl_03_temp
string XX;
double id_01_temp, id_02_temp, id_03_temp;
lbl_XX_temp.Text= "The Device " +XX+ "has" +id_XX_temp+" ℃";
The clean way to concatenate values is to use String.Format
lbl_XX_temp.Text= String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
See MSDN Doc: String.Format()
Maybe, I misunderstood the question. I think the OP wants to convert a string into a valid control right?
Web:
string lblSelected = String.Format("lbl_{0}_temp", XX);
Label lbl = (Label)this.FindControl(lblSelected);
lbl.Text = String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
WinForms:
string lblSelected = String.Format("lbl_{0}_temp", XX);
Control[] ctrl = this.Controls.Find(lblSelected, true);
Label lbl = ctrl[0] as Label;
lbl.Text = String.Format("The Device {0} has {1} ℃", XX, id_XX_temp);
String.Format is actually less performing than a straight string concatenation like your question poses. It's probably a matter of ticks and nanoseconds, but there is more overhead involved with String.Format than just saying a + b + c for string concatenation.
Personally, String.Format looks cleaner to me, but it's not faster.
I would use a pair of arrays or dictionaries (setting them up is left as the proverbial exercise for the reader):
labels[index].Text = "Device " + (index + 1) + " has temperature "
+ temperatures[index].ToString(formatString) + " ℃";
EDIT
From the code in your comment, it seems you want to identify a label by name, and that you will derive the name from an integer variable, like this:
for (int i=1; i<=6; i++)
{
Label label = GetLabelForIndex(i);
//do something with the label here
}
So the question is, how will you get the label for a given index? In other words, what is the implementation of GetLabelForIndex(int)? The answer to that question depends on what kind of Label we're talking about. What library does it come from? Is it WinForms? Silverlight? WPF? If it's WinForms, see Get a Windows Forms control by name in C#. If WPF or Silverlight, see Find WPF control by Name. The accepted answer here also proposes using a dictionary with a string key, which is similar to my suggestion above.
Unless you're doing this thousands of times a second, the performance benefit of using a dictionary is probably insignificant, in which case you should just use Find or FindName directly.
Related
i have a Trackbar and want it to add the Current Value to a richtextbox Text without replacing the whole Text Line
richTextBox1.Rtf = richTextBox1.Rtf.Replace("aimbot_aimtime=85.000000", "aimbot_aimtime=" + trackbarpercent.Text + ".000000");
(i get the Value from my Label)
Thats what im using right now but it only Replaces it if the Text is "aimbot_aimtime=85.000000"
i want it to add the new Value after "aimbot_aimtime=NEWVALUE" but i cant get it to work atm
#Marc Lyon
I think a better way for me is to Replace the Line itself cause its always Line 7
Got it working, thanks to all who helped :)
void changeLine(RichTextBox RTB, int line, string text)
{
int s1 = RTB.GetFirstCharIndexFromLine(line);
int s2 = line < RTB.Lines.Count() - 1 ?
RTB.GetFirstCharIndexFromLine(line + 1) - 1 :
RTB.Text.Length;
RTB.Select(s1, s2 - s1);
RTB.SelectedText = text;
}
private void trackbarpercent_Click(object sender, EventArgs e)
{
changeLine(richTextBox1, 7, "aimbot_aimtime=" + aimtimetrackbar.Value + ".000000");
}
You have to know what the value is in order to replace it, which is why it only works when the value is your default value of 85.
In order to replace the text with the new text, you will have to track the previous value somewhere to use in your replacement. This means a field in your form, a property in some class. Let's say you create an int field on your form (myForm) called oldAimbot_aimtime. Every time the slider changes, put old value into this field. now your code becomes:
var prompt = "aimbot_aimtime=";
var oldvalue = string.Format("{0}{1}", prompt, myForm.oldAimbot_aimtime);
var newvalue = string.Format("{0}{1}", prompt, {NEWVALUE}.Format("#.######");
richTextBox1.Rtf = richTextBox1.Rtf.Replace(oldvalue, newvalue);
This code is off the top of my head and may not work exact, but it should replace the value. What is the value of using a richtextbox on a config screen? Can you post a screenshot?
OK, I see the screenshot. Ethics aside (not sure there is such a thing as a legit aimbot). You are using the richtextbox presumably because it was the easiest control for you to style...
Where you use the richtextbox is probably better suited to a GridView, ListBox, maybe even a treeview where you have finer control over each element.
If you want to use the richtext, write code which emits each option, then you can obtain exact values to use in rtf.Replace()commands
Hope this helps.
I am very new to C#. I learn best by experimentation, but of course, I will get completely stumped sometimes. I will try to explain my problem the best I can with what knowledge of the programming language I currently have.
I have been trying to create a simple tool to edit/add lines of text into a text file. I have done much researching, especially on this site, and all the information has been extremely helpful. My problem though, is adding text to both sides to a single line of text within a multi-line textbox.
So lets say I have a textbox with 2 existing lines; I want to add some text next to both sides of to one of one lines, and do the same to the next one. Here is an example of what the text would look like before and after a button is hit:
Before
is not the same as is different than
After
A is not the same as B A is different than B
The two lines in "Before" would be in textBox1 (multiline), and would be inserted to richTextBox1 as "After".
Hopefully I have explained it clearly enough, I do not know where to begin with this.
Thank you.
If you know which index you have to update the text, then you should be able to inset the value directly using insert function exposed by string class
Example:
//Get the text box value
var formatedTextboxString = this.textbox1.Text;
formatedTextboxString = formatedTextboxString.Insert(0, "A ");
formatedTextboxString = formatedTextboxString.Insert(21, "B");
//Place the formated text back to the richTextBox
this.richTextBox1.Text = formatedTextboxString;
Try
"{0} is not the same as {1} {2} is different than {3}"
In textbox1. Then use:
textbox2.Text = String.Format(textbox1.Text, A, B, A, B);
In case if you have multiline textbox:
var list = new List<string>(textBox1.Lines);
for (int i = 0; i < list.Count; ++i)
{
list[i] = "A" + list[i] + "B";
}
textBox1.Lines = list.ToArray();
string[] arr = textBox1.Text.Split(Environment.Newline);
//then loop over each line and add whatever you want :-
foreach (string s in arr)
{
//add here
}
I guess this is good enough hint to start with :)
I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.
So I want to have a number that can be added to but then written out in a label. I'm doing it in Visual C#.NET.
For example, if I had code like this (either in a timer or while loop):
int i = 0;
i = i + 5;
label4 = "Current Number of Views: " + i.ToString();
I can't use ToString() to convert it to a string. So how would I make i displayable
While I don't understand why you can't use i.toString(), I suppose that you could also use something like
label4.Text = String.Format("Current Number of Views: {0:d}", i);
This should yield the same result.
Edit: as #BiggsTRC points out (which I didn't think of), your error is probably a result of not assigning to the right variable. You probably should access the property label4.Text to assign to. The code example fixes this properly now.
u could use String.Format without explicitly using ToString()
label4.Text = String.Format("Current Number of Views: {0}", i);
This should work. The one issue i see is the label itself. It should look like this:
label4.Text = "Current Number of Views: " + i.ToString();
I dont understand why cant you use i.ToString(). By default, i is assigned with 0 value and hence, i.ToString() would not throw any exception.
if you are using WPF , then you should assign the value to the content property of the label.
label4.Content = "Current Number of Views: " + i.ToString();
Following code, credit: Guffa.
Hello All,
I'm trying to add controls to a Form at runtime based on the information found in a Plain Text File. The structure? of the text file is always the same, and will not change. Example:
File.txt:
Label
"This is a label"
320, 240
Explanation:
Control
Text
Location
The following code, provided to me by Guffa, doesn't cause any errors or anything, but at the same time, nothing happens at all. And I'm not sure why... Can somebody please explain why the label doesn't get created and added to the form with the right info attached to it?
MatchCollection lines = Regex.Matches(File.ReadAllText(fileName), #"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n");
foreach (Match match in lines) {
string control = match.Groups[1].Value;
string text = match.Groups[2].Value;
int x = Int32.Parse(match.Groups[3].Value);
int y = Int32.Parse(match.Groups[4].Value);
Console.WriteLine("{0}, \"{1}\", {2}, {3}", control, text, x, y);
if(control == "Label")
{
Label label = new Label();
label.Text = text;
canvas.Controls.Add(label); // canvas is a Panel Control.
label.Location = new Point(x, y);
}
}
I hope that I have clearly explained my situation. Any help at all would be greatly appreciated.
Thanks for taking the time to read.
jase
My guess is that your file doesn't have quite the right format. If you step into the code, does it match anything?
If so, what gets printed to the console?
Have you tried it with the exact sample shown in the question? While I haven't tried it in a form, I've tried the rest of the code above with the sample file, and it works fine.
Personally I don't think I'd use a regex to match all of the lines like this - it makes it harder to diagnose issues - but it should work okay if the file is correct. You say you don't understand the regex provided - that's another good reason not to use it, to be honest. Even if it's entirely correct, it's not a good idea to use code that you don't understand - you won't be able to maintain it.
I would personally just read the lines three at a time and then deal with them that way. Something like this:
private static readonly Regex LocationPattern = new Regex(#"^(\d+), (\d+)$");
...
using (TextReader reader = File.OpenText(filename))
{
while (true)
{
string control = reader.ReadLine();
string text = reader.ReadLine();
string location = reader.ReadLine();
if (control == null)
{
break;
}
if (text == null || location == null)
{
// Or however you want to handle this...
throw new InvalidConfigurationFileException
("Incorrect number of lines");
}
if (text.Length < 2 || !text.StartsWith("\"") || !text.EndsWith("\""))
{
// Or however you want to handle this...
throw new InvalidConfigurationFileException
("Text is not in quotes");
}
text = text.Substring(1, text.Length - 2);
Match locationMatch = LocationPattern.Match(location);
if (!locationMatch.Success)
{
// Or however you want to handle this...
throw new InvalidConfigurationFileException
("Invalid location: " + location);
}
// You could use int.TryParse if you want to handle this differently
Point parsedLocation = new Point(int.Parse(match.Groups[1].Value),
int.Parse(match.Groups[2].Value));
// Now the rest of the code before
}
}
As you can tell, it's a lot more code - but each part of it is relatively simple. Regular expressions are powerful if you're happy to handle them, but unless something is complicated to express "longhand" I often find it easier to maintain the longer way. Just a personal preference though.
Blind guess: I see the last \r\n in the regex is not optional. Possible that your input file is missing a return character after the last line?
Additional note about sucking at regular expressions: there are some tools that will help you experiment with regular expressions, which might be useful, for example, to understand what's going on in this particular case. I always use Expresso, which among other things analyzes the structure of the regular expression you provide and explains what it does.
Another possibility is that you forgot to add canvas (Panel control) to another control so the chain of controls inside canvas is not displayed and you would maybe not see that the canvas itself doesn't display. Which guess is the best? :-)