How I can have a string value like "PropertyBag["ABCD"]" ? I want it to assign to a value of a chart in my WPF App. I am using it like as shown below :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ViewModel vm = new ViewModel();
foreach (var str in vm.Data)
{
string name = "ABCD";
LineSeries lineSeries = new LineSeries();
lineSeries.ItemsSource = new ViewModel().Data;
lineSeries.XBindingPath = "Date";
lineSeries.YBindingPath = "PropertyBag[\" + name + \"]"; // here i am getting error saying - Input string was not in a correct format
lineSeries.IsSeriesVisible = true;
lineSeries.ShowTooltip = true;
chart.Series.Add(lineSeries);
}
this.DataContext = vm;
}
I want it like
lineSeries.YBindingPath = "PropertyBag["ABCD"]" //
(should include all 4 double quotes). How it is possible ??
I tried this also, but still same error :
lineSeries.YBindingPath = String.Format(#"PropertBag[""{0}""]", name);
This must work and it is a more elegant solution:
string name = "ABC";
lineSeries.YBindingPath = string.Format("\"PropertyBag[\"{0}\"]\"", name);
You escaped the quote before and after name, in doing that you didn't specify where the first part of the string ends and where the second one starts. To avoid errors like that it is better to use the Format method. It makes code easier to read and maintain.
The following solution:
string.Format(#"""PropertyBag[""{0}""]""", name)
is good too, but I think the first one is more readable. I personally like more the first one. But it is up to you, just avoid concatenation; in modern programming it is deprecated especially when the language has more efficient and powerful tools to do the job.
You're escaping the quotes before the pluses, meaning they get interpreted as characters, not as addition operators. You need to add additional quotation marks, like so:
lineSeries.YBindingPath = "\"PropertyBag[\"" + name + "\"]\"";
This way, you define two new strings; a prefix and a suffix to the name variable.
You can also use string interpolation, which results in cleaner code:
lineSeries.YBindingPath = $"\"PropertyBag[\"{name}\"]\"";
Quoted string literals
("PropertyBag[\"" + name + "\"]");
Verbatim string literals
(#"PropertyBag[""{0}""]", name);
Try Raw string literals if you're on C# 11
Related
I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.
My Goal: I want to parse a file and display it in a textbox. Here's the code (thanks to Aviral Singh).
private void Form1_Load(object sender, EventArgs e)
{
var path = #"C:\Users\Smith\Desktop\Settings.txt"; //Path to settings file.
RichTextBox rtb = new RichTextBox();
System.IO.StreamReader sis = new System.IO.StreamReader(path);
rtb.Text = sis.ReadToEnd();
sis.Close();
foreach (string line in rtb.Lines)
{
if (line.Contains("Installation Technical Manual:") == true)
{
string numbers = line.Substring(line.IndexOf("Installation Technical Manual:"));
textBox1.Text = numbers;
}
}
}
Text file looks like this:
My Problem: The textbox in my program displays entire line: Installation Technical Manual: (1234567890).
I just want the number with brackets (1234567890). to be displayed in the textbox. What changes should I make to the code to remove the words and just display numbers with brackets around it? Thanks for your help. :)
numbers = "(" + new String(numbers.Where(Char.IsDigit).ToArray()) + ")";
The problem is that IndexOf() is going to give you the starting position of the string which you're asking for the index of. Which in your example is going to be 0, so a Substring call that starts at 0 is going to return you the entire string.
What you really want to do is Substring(IndexOf("Installation Technical Manual:") + "Installation Technical Manual:".Length). That will give you whatever comes after your string.
Assuming you have ':' in your line always,
if(line.Contains(":"))
{
string numbers = line.Split(':')[1];
textBox1.Text = numbers;
}
The reason your code is not working as you have used the substring method as with one parameter, so it is used as :
public string Substring(
int startIndex
)
See: http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx
And you are passing in, line.IndexOf("Installation Technical Manual:")
which will return ).
See here: http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
So you are essentially saying return Substring of string Installation Technical Manual:(number) starting at 0 which basically returns the whole line.
I want to access the font-family name out of the following string and then after applying a filter on the name i want to put it back. Here is my string :
font-size:36px;font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;text-align:center;line-height:125%;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:middle;fill:#6b055f;fill-opacity:1;stroke:none;font-family:Abel;-inkscape-font-specification:'Abel, Semi-Bold'
How can i do this in c# ?
You can use the String class, which exposes all the methods you need to get cracking with this. For instance, use String.IndexOf to find the index of a character or string, and String.Substring to extract, then you can use String.Replace.
That should be sufficient to make a start, if you have a specific question related to a problem, then ask that.
You can use Regex.Replace:
string test = "stroke:none;font-family:Abel;-inkscape-font-specification:'Bickham Script Pro Semibold, Semi-Bold'";
// search for the font style
Regex rex = new Regex(";font-family:.*;");
// replace the font with a new font
string newString = rex.Replace(test,";font=famliy:Arial;");
I would use the power of ASP.NET instead of parsing the string myself. Why reinvent the wheel?
string style = "font-size:36px;font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;text-align:center;line-height:125%;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:middle;fill:#6b055f;fill-opacity:1;stroke:none;font-family:Abel;-inkscape-font-specification:'Abel, Semi-Bold'";
System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label();
label.Style.Value = style;
label.Style["font-family"] = "Verdana";
style = label.Style.Value;
label.Dispose();
This will work also in WinForms, you just have to add reference to the System.Web assembly.
You could do something like this:
public static class CssStyle
{
public static string Update(string style, string key, string value)
{
var parts = style.Split(';');
for (int i = 0; i < parts.Length; i++)
{
if (parts[i].StartsWith(key))
{
parts[i] = key + ":" + value;
break;
}
}
return string.Join(";", parts);
}
}
Which would allow you to have a generic function which could update any part of the style. You could also extend it to add the style if it does not already exist.
Basically our Problem is:
We can't replace a string like this: 10003*
But we can replace a string like this: 10003
we want to replace a part of a string that looks like this: 10003*
This is our Code:
string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
string SelectedItem = lstTxt.SelectedItem.ToString() + "*";
text = text.Replace(SelectedItem, "tietze111");
if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
lstTxt.SelectedIndex++;
loop++;
}
sw2.Write(text);
But it doesn't work. When we leave out the * in the part to replace, it works. But we have to replace the * too. Do you know what we have to change?
It works when we use this:
string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
string SelectedItem = lstTxt.SelectedItem.ToString(); // changed
text = text.Replace(SelectedItem, "tietze111");
if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
lstTxt.SelectedIndex++;
loop++;
}
sw2.Write(text);
--
using (var sr2 = new StreamReader(Application.StartupPath + #"\website\Dehler 22 ET.htm", Encoding.Default))
{
using (var sw2 = new StreamWriter(tempFile, true, Encoding.Default))
We are using this because the file is still in ASCII. Maybe that is the problem.
How do we solve this?
Fix the following line,
string SelectedItem = lstTxt.SelectedItem.Value;
You are taking the item and not the value.
Have you tried?
"[\*]"
Or
#"[*]"
The String.Replace(String,String) method doesn't do anything special with any characters. There is a character in your id that you are trying to replace is not the same as the one you are trying to match on. I would try copying the astrisk from the data source into your code and see if the problem still exists.
Your problem * is encoded in some other type. The Unicode value for asterisk U+002A
You could try this. Note Char.MinValue is technically a null value since you cannot have a blank Char.
In your case: lstTxt.SelectedItem.ToString() + '\u002A'.ToString();
If that doesn't work try removing (using different encoded values for *) to make sure you can actually find it in the string.
SomeString.Replace('\u002A', Char.MinValue);
OR
SomeString.Replace('\u002A'.ToString(), String.Empty);
I've ran into issues like this before and it ends up being a trial and error kind of thing until you get it right. Similar problem I had last summer C# String.Replace not finding / replacing Symbol (™, ®)
I'm developing a piece of software in C# and the end result is an Excel spreadsheet. The title of the spreadsheet is created using several variables to explain exactly what the spreadsheet is. One of the variables is a string which contains data like this:
'1.1.1'
I need to convert it at the point of creating the spreadsheet to be:
'1_1_1'
I have tried using the String.Replace method but it just seems to ignore it. Any ideas?
Best Regards
I bet you doing this:
myString.Replace(".","_");
When you should be doing this:
myString = myString.Replace(".","_");
Remember, in .Net strings are immutable, so any changes result in a new string.
Chances are you're ignoring the result of string.Replace. You need:
text = text.Replace('.', '_');
Just calling Replace doesn't change the existing string - it creates a new string and returns it. Strings are immutable in .NET - they never change after creation.
When you use string.Replace are you remembering that you have to assign it?
yourString.Replace(".", "_");
Will do nothing.
string newString = yourString.Replace(".", "_");
will return the string with the dots replaced with underscores.
If I had to guess, you're not capturing the value returned by String.Replace. Strings are immutable, so String.Replace returns a new string, which you need to store a reference to.
string foo = "1.1.1";
foo = foo.Replace('.', '_');
String input = "1.1.1";
input = input.Replace(".", "_");
strings are immutable, so make sure you're using it like this:
string myString = "1.1.1";
myString = myString.Replace('.', '_');
String.Replace is the right way to do this:
private void button1_Click(object sender, RoutedEventArgs e) {
String myNumbers = "1.1.1";
Console.WriteLine("after replace: " + myNumbers);
myNumbers = myNumbers.Replace(".", "_");
Console.WriteLine("after replace: " + myNumbers);
}
will produce:
after replace: 1.1.1
after replace: 1_1_1