C#, label ignores parts of the given text - c#

i need to put in my label something like "x rub | y%" but label ignores the rest of text after the x.
when the label gets "0" value, it works as i want it to, i.e. "0$. | 0%", but whenever the value isnt 0, it only displays "read_cat"'s value ("2000"). Thank you in advance.
System.IO.StreamReader reading2 = File.OpenText("categories\\clothes.txt");
read_cat1 = Convert.ToString(File.ReadAllText("categories\\clothes.txt"));
clothes_percentage.Text = Convert.ToString(read_cat1) +"$ | "+
Convert.ToString(Math.Round(Convert.ToDouble(read_cat1) * 100 / salary, 2))+"%";
reading2.Close();

My guess is that your file contains a linebreak after the actual value. Use the Trim() method to remove linebreaks and other whitespace from the string you read from the file.
string read_cat1 = File.ReadAllText("categories\\clothes.txt");
read_cat1 = read_cat1.Trim();
clothes_percentage.Text = read_cat1 + "$ | " +
Math.Round(Convert.ToDouble(read_cat1) * 100 / salary, 2) +"%";

Related

c sharp Programming , .net framework [duplicate]

This question already has answers here:
Formatting a C# string with identical spacing in between values
(7 answers)
Closed 3 years ago.
I have some code and string i want the string to be fixed length of 15 if
string length is less than 15 than i want to add spacing to make my string 15 character wide for printing purpose
i have tried
(string.format("{xxxxxxxxxxxxxxx}",myRow.Cells["PREMIER REG"].Value.ToString())
Input string was not in correct format exception thrown
myGraphic.DrawString("S# | DESCRIPTION | QTY | PRICE
| SUBTOTAL", myFont, Mybrash, xMargin, ySpacing);
ySpacing += 7;
myGraphic.DrawLine(myPen, xMargin, yMargin, 50, 0);
ySpacing += yMargin;
foreach (DataGridViewRow myRow in dataGridViewBill.Rows)
{
int i = 1;
myGraphic.DrawString(
i+ "" +
myRow.Cells["gvProductTitle"].Value.ToString() +
myRow.Cells["gvQuantity"].Value +
myRow.Cells["gvPrice"].Value +
myRow.Cells["gvTotal"].Value
, myFont, Mybrash, xMargin, ySpacing);
ySpacing += yMargin;
}
The problem in printing gvquantity value is being to pulled to product column
try this:
myRow.Cells["gvQuantity"].Value.ToString().PadRight(15);
String formatting allows you to specify the width (and whether to left or right align) by putting a comma after the format specifier and then the field width like:
string.format("{0,15}", myRow.Cells["PREMIER REG"].Value.ToString());
See
https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=netframework-4.8#controlling-formatting

Line up Characters

I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"
Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')
Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm

Format text by adding whitespace

I am trying to format strings by whitespaces.
All strings normally look like
01. Anton 30p
02. Cinderella 20p
03. Thomas 18p
04. Anastacia-Laura 16p
I want to format each string, that the points start at the same column.
There I wrote:
s = stringUpToName;
int addSpacing = 37 - s.Length;
for (int i = 0; i < addSpacing; i += 1) s += " ";
s += points;
It gets closer this way, but it's still not perfectly formatted.
I want it to look like this:
01. Anton 30p
02. Cinderella 20p
03. Thomas 18p
04. Anastacia-Laura 16p
Use "0" custom specifier as zero-placeholder symbol to format index/number of record. 0:00 will give you 01 for value 1.
Also keep in mind that item format syntax is { index[,alignment][:formatString]} where alignment indicates preferred formatted field width. So, adding alignment to second item format {1,20} gives you right-aligned field width of 20 characters. With negative alignment field will be left-aligned.
Total format string will look like "{0:00}. {1,-20}{2}p"
You can use it with String.Format or StringBuilder.AppendFormat if you are build string, or Console.WriteLine if you are writing it to console.
int index = 1;
string name = "Anton";
int points = 30;
var result = String.Format("{0:00}. {1,-20}{2}p", index, name, points)
// "01. Anton 30p"
String.Format and Composite Formatting using the Alignment functionality
string[] names = new string[]
{
"1. Anton 30p",
"2. Cinderella 20p",
"3. Thomas 18p",
"4. Anastacia-Laura 16p"
};
foreach(string s in names)
{
int lastSpace = s.LastIndexOf(' ');
int firstSpace = s.IndexOf(' ');
string result = string.Format("{0,-4}{1,-37}{2,4}", s.Substring(0, firstSpace), s.Substring(firstSpace + 1, lastSpace), s.Substring(lastSpace+1));
Console.WriteLine(result);
}
Keep in mind that to see the output exactly aligned in columns you need to use a Fixed Width font like Lucida Console or Courier, because fonts with variable width use less pixel to print an I than to print a W.
Try right-align the numbers using
String.Format("{0} {1} {2,4}p",
Num,
Name,
Point);

textbox with arabic language

I have a problem with a textbox. the problem is that I initialized the property
textBox1.RightToLeft = RightToLeft.Yes;
and when I typed arabic characters it types correctly but the problem if I type the following
string
66/ج ح /
96
the number 96 after the / but the editor doesn't allow to write it that way so when I read it it change its characters like this :
ج ح/66/96
var LRM = ((char)0x200E).ToString();
lbldate.Text = ddlTrnNoYears.SelectedItem.Text+'/' + LRM + ddlTrainingMonth.SelectedItem.Text + LRM +'/'+ddlTrainingDay.SelectedItem.Text;
Result :
۳۹۹/‎مرحبا‎/۳

Format a string into columns

Is there a cool way to take something like this:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
and format it to something like this:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
Using string format commands?
I am not too hung up on what to do if one is very long. For example this would be ok by me:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
Super Town person - Long Town Name, WA- 45648
To provide some context. I have a drop down box that shows info very similar to this. Right now my code to create the item in the drop down looks like this:
public partial class CustomerDataContract
{
public string DropDownDisplay
{
get
{
return Name + " - " + City + ", " + State + " - " + ID;
}
}
}
I am looking for a way to format this better. Any ideas?
This is what I ended up with:
HttpContext.Current.Server.HtmlDecode(
String.Format("{0,-27} - {1,-15}, {2, 2} - {3,5}",
Name, City, State, ID)
.Replace(" ", " "));
The HtmlDecode changes the to a space that can withstand the space removing formatting of the dropdown list.
You can specify the number of columns occupied by the text as well as alignment using Console.WriteLine or using String.Format:
// Prints "--123 --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "-- 123--"
Console.WriteLine("--{0,10}--", 123);
The number specifies the number of columns you want to use and the sign specifies alignment (- for left alignment, + for right alignment). So, if you know the number of columns available, you could write for example something like this:
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
If you'd like to calculate the number of columns based on the entire list (e.g. the longest name), then you'll need to get that number in advance and pass it as a parameter to your DropDownDisplay - there is no way to do this automatically.
In addition to Tomas's answer I just want to point out that string interpolation can be used in C# 6 or newer.
// with string format
var columnHeaders1 = string.Format($"|{0,-30}|{1,-4}|{2,-15}|{3,-30}|{4,-30}|{5,-30}|{6,-30}", "ColumnA", "ColumnB", "ColumnC", "ColumnD", "ColumnE", "ColumnF", "ColumnG");
// with string interpolation
var columnHeaders2 = $"|{"ColumnA",-30}|{"ColumnB",-4}|{"ColumnC",-15}|{"ColumnD",-30}|{"ColumnE",-30}|{"ColumnF",-30}|{"ColumnG",-30}";
I am unable to add a comment above, but in the accepted answer it was stated:
If you'd like to calculate the number of columns based on the entire list (e.g. the longest name), then you'll need to get that number in advance and pass it as a parameter to your DropDownDisplay - there is no way to do this automatically.
This can in fact be done programmatically at runtime by creating the format string 'on the fly':
string p0 = "first";
string p1 = "separated by alignment value x";
int x = n * 10; // calculate the alignment x as needed
// now use x to give something like: {0,-20}, {1}
string fmt = "{0,-" + x + "},{1}"; // or whatever formatting expression you want
// then use the fmt string
string str = string.Format(fmt, p0, p1)
// with n = 2 this would give us
"first ,separated by alignment value x"

Categories

Resources