I'm trying to print random dates in the format of Date-newline-Date-newline etc but dynamically add the dates from some c# code.
The current code I am using is shown below prints dates in one line with a space instead of a newline.
Here is my current code
private void WriteDates(int NumberOfDates)
{
string dates = "";
for(int i = 0 ; i < NumberOfDates; i++)
{
var print = RandomDay().ToShortDateString().ToString();
dates += print + "\n";
}
LblDate.Text = dates;
}
\n is a special "line feed" character that doesn't create a line break in the browser's rendering of the HTML. It will create a line break in the HTML file itself, but the browser doesn't take this into consideration when it renders out the markup.
Look at the source of the page,(Chrome -> Developer tools) and you will see the line break within the Label element..
Try br tag instead.
Try to avoid for loop where you can use LINQ:
private void WriteDates(int NumberOfDates)
{
LblDate.Text = string.Join(string.Empty,
Enumerable.Range(0, NumberOfDates)
.Select(n => $"{RandomDay().ToShortDateString()}<br />"));
}
Related
So in this example I attempted to make a program that inserts a "*" in between every character that is in a certain textbox (textBox1). Though I'm having trouble figuring it out. Yes I have looked around on stack-overflow already, nothing seems to relate/work with what I'm trying to do.
Here's the code I have currently:
for (int i = 1; i <= textBox1.Text.Length; i += 1)
{
textBox2.Text = textBox1.Text.Insert(i, "*");
i++;
}
Here is a picture of what this current code does:
pretty easy to do like...
textBox2.Text = string.Join('*', textBox1.Text.ToCharArray())
You're doing a whole lot of unnecessary things. I'm using two strings instead of text boxes as I'm on Console, but the idea is the same.
var tb1Text = "hello";
var tb2Text = string.Empty;
foreach (var ch in tb1Text)
{
tb2Text += ch + "*";
}
tb2Text = tb2Text.TrimEnd(new char[] { '*' });
We iterate through the string (because a string is essentially an array of char), and add it to the tb2Text along with a trailing *. If you don't want a trailing * at the very end, use the last line of code, otherwise get rid of it.
Result
tb1Text = hello
And
tb2Text = h*e*l*l*o
I wish to preserve the italics in the text while removing all the empty lines. I can't seem to be able to do it.
I used this code. It removes the empty lines but the text the italics.
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
The Golden Rule about RichTextBoxes is to never change the Text directly, once it has any formatting.
To add you use AppendText and to change you need to use the Select, Cut, Copy & Paste.. methods to preserve the formatting!
string needle = "\r\r"; // only one possible cause of empty lines
int p1 = richTextBox1.Find(needle);
while (p1 >= 0)
{
richTextBox1.SelectionStart = p1;
richTextBox1.Select(p1, needle.Length);
richTextBox1.Cut();
p1 = richTextBox1.Find(needle);
}
For multiple needles you'll need to call the code multiple times, I'm afraid..
You can try removing empty lines from its Rtf Text. The sample code given below will work for you.
String[] allLines = richTextBox1
.Rtf
.Split( new string[] { Environment.NewLine },StringSplitOptions.None);
dynamic linesWithoutEmptyLines = from itm in allLines
where itm.Trim() != "\\par"
select itm;
richTextBox1.Rtf = string
.Join(Environment.NewLine, linesWithoutEmptyLines);
It will preserve the formatting of text and going to remove all the empty lines.
I am trying to read lines from txt file into array and display it into a text box.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack != true)
{
blogPostTextBox.Text ="";
string blogFilePath = Server.MapPath("~") + "/Blogs.txt";
string[] blogMessageArray = File.ReadAllLines(blogFilePath);
// this for loop code does not work..I think..
for (int i = 0; i < blogMessageArray.Length; i++)
{
string[] fileLineArray = blogMessageArray[i].Split(' ');
blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString();
}
}
}
My text file contains several line and I am trying to split each line to array and display all lines into a text box using a for loop or while loop.
UPDATE:
For ASP.Net
var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x));
blogPostTextBox.Text=string.Join(Environment.NewLine, items)
and as a side note, it is better to use Path.Combine when you build path from multiple strings
string blogFilePath = Path.Combine( Server.MapPath("~") , "Blogs.txt");
also if (IsPostBack != true) is valid but you can do as
if (!IsPostBack)
Winform
If the Multiline property of the text box control is set to true, you can use TextBoxBase.Lines Property
blogPostTextBox.Lines =File.ReadAllLines(blogFilePath);
if you need to split each line and set as textbox text then
blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray();
You have to set TextMode="MultiLine" in your TextBox(default value is SingleLine), then you could build the text with Linq in this way:
var allLinesText = blogMessageArray
.SelectMany(line => line.Split().Select(word => word.Trim()))
.Where(word => !string.IsNullOrEmpty(word));
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText);
You need to append each line to the textbox. What you are doing above is overwriting the contents of the textbox with each new line.
string[] blogMessageArray = File.ReadAllLines("");
blogPostTextBox.Text = "";
foreach (string message in blogMessageArray)
{
blogPostTextBox.Text += message + Environment.NewLine;
}
Although rather than read in all the lines, and then write out all the lines, why don't you just write out all the text to the textbox?
blogPostTextBox.Text = File.ReadAllText();
Though you could do this in a loop, you really don't need to (or want to)
Replace your loop with with built in dot net methods that actually do what your need.
See String.Join()
public static string Join(
string separator,
params string[] value
)
This will combine all of the elements of blogMessageArray with your specified separator
('\n' in your case, HTML does not need "\r\n")
Then just assign this to the property blogPostTextBox.Tex
i have comma separated values like English,Science in lblsubject.text which i am separating using the code below.
The code given below displays Science in both the Label1 as well as Label2 as it gets overridden...but I want to display English in one label and science in another label.
how to do it...pls help..!
string[] lines = Regex.Split(lblsubject.Text, ",");
foreach (string line in lines)
{
Label1.Text = line;
Label2.Text = line;
}
You will get two elements in the array, why are you using the foreach loop. you can do
Label1.Text = lines[0];
Label2.Text = lines[1];
You might want to add labels dynamically, if you don't know how many there will be. (Note also, Regex.Split is overkill for this, you could just use the String.Split extension method.)
string[] lines = lblsubject.Text.Split(',');
for (int i=0 ; i<lines.Length ; i++)
{
var newLabel = new Label();
newLabel.Text = lines[i];
form1.Controls.Add(newLabel);
}
Where form1 could be any container control that you want to add your labels to.
Another alternative could be to add HTML directly to your output. Something like this:
var html = string.Join("<br/>",
lblsubject.Text.Split(',').Select(
category => string.Format("<div>{0}</div>", category)
)
);
panel1.Controls.Add(new LiteralControl(html));
(Where again, panel1 is just a container for your output.)
Edit, per comment
DrowDownList1.Items.AddRange(
lblsubject.Text.Split(',')
.Select(category => new ListItem(category))
.ToArray()
);
Use Split() function
string[] lines = lblsubject.Text.Split(',');
Label1.Text = lines[0];
Label2.Text = lines[1];
fairly new to C# here......What I'm trying to do is parse a bunch of text to a webpage from a .txt file uploaded to memory.
Here's what the .txt file looks like
.RES B7=121
.RES C12=554
.RES VMAX=4.7μV
Again, it goes on like this for another 50 or so .RES'...
I've successfully got it to parse, but not in the desired format...
Here's how I want it to look on the webpage
B7.........121
C12.........554
VMAX.........4.7μV
all inside of a hidden panel with id="outpt"... which is currently set to visible="false"
Here's the code i'm using in my C# Page
namespace Sdefault
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpld_Click(object sender, EventArgs e)
{
Stream theStream = file1.PostedFile.InputStream; //uploads .txt file to memory for parse
using (StreamReader sr = new StreamReader(theStream))
{
string tba;
while ((tba = sr.ReadLine()) != null)
{
string[] tmpArray = tba.Split(Convert.ToChar("=")); //Splits ".RES B7=121" to "B7"... but for some reason, It prints it as
//".RES B7.RES C12.RES VMAX"... I would ultimately desire it to be printed as shown above
Response.Write(tmpArray[0].ToString());
var.Text = tba;
outpt.Visible = true;
}
}
}
}
}
Any pointers in which direction I should go with this?
// Open the file for reading
using (StreamReader reader = new StreamReader((Stream)file1.PostedFile.InputStream))
{
// as long as we have content to read, continue reading
while (reader.Peek() > 0)
{
// split the line by the equal sign. so, e.g. if:
// ReadLine() = .RES B7=121
// then
// parts[0] = ".RES b7";
// parts[1] = "121";
String[] parts = reader.ReadLine().split(new[]{ '=' });
// Make the values a bit more bullet-proof (in cases where the line may
// have not split correctly, or we won't have any content, we default
// to a String.Empty)
// We also Substring the left hand value to "skip past" the ".RES" portion.
// Normally I would hard-code the 5 value, but I used ".RES ".Length to
// outline what we're actually cutting out.
String leftHand = parts.Length > 0 ? parts[0].Substring(".RES ".Length) : String.Empty;
String rightHand = parts.Length > 1 ? parts[1] : String.Empty;
// output will now contain the line you're looking for. Use it as you wish
String output = String.Format("<label>{0}</label><input type=\"text\" value=\"{1}\" />", leftHand, rightHand);
}
// Don't forget to close the stream when you're done.
reader.Close();
}
Not sure on your formatting, but a simple Split and Format will do the trick.
On your split, you're getting everything before the = sign, whereas from your description, you want everything after it. e.g.
while(...)
{
var line = String.Format("<label>{0}< />.........textbox>{0}< />",tba.Split('=')[1]);
Response.Write(line);
}
if you take .RES B7=121 and split it on "=" then the index 0 would be .RES B7 and index one would be 121
if you want to further subdivide you wil have to split index 0 again using Chr(32) which would yield .RES as 0 and B7 as 1.
Can be done inline as suggested above with string formatting.
It looks as though you want someling like
String.Format("<label>{0}< />.........textbox>{1}< />",tba.Split('=')[0].Split(' ')[1],tba.Split('=')[1].);
Ok.. you have several issues here..
first, you are spliting using the =.. so you are splitting the string in two parts...
.RES B7=121 comes to:
tmpArray[0] = .RES B7
tmpArray[1] = 121
To avoid another split, the best you can do is to replace .RES with and empty string:
tmpArray[0] = tmpArray[0].replace(".RES","");
Then, you should be showing this somewhere on your page, so you should be writting:
Response.Write("<label>" + tmpArray[0].ToString() + "< />" + "<textbox>" + tmpArray[1].ToString() + "< />");
Looks like you need to do 2 splits:
1st var tmpArr1 = tba.Split(' ') will result in a string array {".RES","B7=121"}
2nd var tmpArr2 = tmpArr1[1].split('=') will result in a string array {"B7","121"}
Then you can do:
var line = String.Format("<label>{0}</label><textbox>{1}</textbox>",tmpArr2[0],tmpArr2[1]);
Response.Write(line);