Environment.NewLine Does Not Put Each entry On New Row - c#

I have the following code which is to display an address but it does not seem to put each address row on a new line and cant figure out why
var selectedOrigoScheme = origoCedingSchemes.Where(x => x.complyingFundId.ToString() == SelectedSchemeId).ToList();
string origoName = !String.IsNullOrEmpty(selectedOrigoScheme[0].origoName) ? selectedOrigoScheme[0].origoName + Environment.NewLine : "";
string propertyName = !String.IsNullOrEmpty(selectedOrigoScheme[0].propertyName) ? selectedOrigoScheme[0].propertyName + Environment.NewLine : "";
string streetNumber = !String.IsNullOrEmpty(selectedOrigoScheme[0].streetNumber) ? selectedOrigoScheme[0].streetNumber + Environment.NewLine : "";
string street = !String.IsNullOrEmpty(selectedOrigoScheme[0].street) ? selectedOrigoScheme[0].street + Environment.NewLine : "";
string street2 = !String.IsNullOrEmpty(selectedOrigoScheme[0].street2) ? selectedOrigoScheme[0].street2 + Environment.NewLine : "";
string suburb = !String.IsNullOrEmpty(selectedOrigoScheme[0].suburb) ? selectedOrigoScheme[0].suburb + Environment.NewLine : "";
string district = !String.IsNullOrEmpty(selectedOrigoScheme[0].district) ? selectedOrigoScheme[0].district + Environment.NewLine : "";
string postcode = !String.IsNullOrEmpty(selectedOrigoScheme[0].postcode) ? selectedOrigoScheme[0].postcode + Environment.NewLine : "";
string Origoaddress = origoName + propertyName + streetNumber + street + street2 + suburb + district + postcode;
viewData["Origoaddress"] = Origoaddress;
When I debug I get the following result:
Aviva\r\nNorwich Business Capture Centre\r\nPO Box 520\r\nNorwich\r\nNR1 3WG \r\n
If I look at the result in text visualizer it displays correctly:
Aviva
Norwich Business Capture Centre
PO Box 520
Norwich
NR1 3WG
But if I look at it using HTML visualizer it displays as:
Aviva Norwich Business Capture Centre PO Box 520 Norwich NR1 3WG
Which is how its showing in my address field on the website.
What am I doing wrong as I cant see the issue.
HTML
<%=Html.TextBox("Origoaddress", ViewData["Origoaddress"].ToString())%>

Html ignores white spaces so is ignoring the line breaks you have added. If you were working in pure html you'd need to use < br>. Html.TextBox only supports single line strings so doesn't add line breaks that Html will understand.
In order to use multiple lines you will probably need to use TextArea. See creating multiline textbox using Html.Helper function
for further details.

Related

Populating a Textbox with a Text File but it always adds a blank first line?

I have a file containing text and I can get it to populate a textbox on page load but it always adds a blank first line. Any ideas? I've tried skipping the first line in the array in case it was blank (both 0 and 1) but 0 does nothing and 1 skips the first line in the text file.
I've also tried to set the textbox to null and "" first in case it was appending to the textbox in some way.
//Populating the contents box
string[] str = null;
if (File.Exists(docPath + prefix + libIDPath + "\\" + oldFileName))
{
str = File.ReadAllLines(docPath + prefix + libIDPath + "\\" + oldFileName);
//str = str.Skip(0).ToArray();
//FDContentsBox.Text = null;
}
foreach (string s in str)
{
FDContentsBox.Text = FDContentsBox.Text + "\n" + s;
}
In your foreach you are appending the "\n" before appending the string itself. Try
FDContentsBox.Text = FDContentsBox.Text + s + "\n";
instead.
Please try this, there is no need to read all lines nor a foreach loop
var filePath = docPath + prefix + libIDPath + "\\" + oldFileName;
if (File.Exists(filePath))
{
FDContentsBox.Text = File.ReadAllText(filePath);
}

Add double quotes to variable name for MS Deploy code in c#

Its a c# code written in a SSIS script task component.
PS_script + #"""$compname = " "\" + Row.computername"\" +
"$appname =" + Row.applicationname + " $appvalue = " + Row.appvalue +
"";
I am tying the MS deploy and setting params coming from table driven. The above statement throws error as I am not able to pass double quotes in computername param.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
In C#, a literal string with the prefix #, "" will be replaced by ".
Example :
var str = #"$compname = """ + Row.computername + #"""";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
You can also escape a character with \. Then \" will be replaced by ".
Example :
var str = "$compname = \"" + Row.computername + "\"";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
In you case, you can also use string.Format to more lisibility :
string.Format(
#" $compname = ""{0}"" $appname = ""{1}"" $appvalue = ""{2}""",
Row.computername, Row.applicationname, Row.appvalue
);
Warning, with SSIS script task, you can't use string interpolation (the literal string prefix $).

C# creating an HTML line with escaping

I'm creating a loop in which each line is a pretty long HTML line on the page. I've tried various combinations of # and """ but I just can't seem to get the hang of it
This is what I've got now, but the single quotes are giving me problems on the page, so I want to change all the single quotes to double quotes, just like a normal HTML line would use them for properties in the elements:
sOutput += "<div class='item link-item " + starOrBullet + "'><a href='" + appSet + linkID + "&TabID=" + tabID + "' target=’_blank’>" + linkText + "</a></div>";
variables are:
starOrBullet
appSet
LinkID
tabID (NOT $TabID=)
linkText
BTW, appSet="http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID="
Can someone help me here?
You have to escape the double quotes (") with \"
For your case:
sOutput += "<div class=\"item link-item " + starOrBullet + "\"><a href=\"" + appSet + linkID + "&TabID=" + tabID + "\" target=’_blank’>" + linkText + "</a></div>";
If you concat many strings, you should use StringBuilder for performance reasons.
You can use a verbatim string and escape a double quote with a double quote. So it will be a double double quote.
tring mystring = #"This is \t a ""verbatim"" string";
You can also make your string shorter by doing the following:
Method 1
string mystring = #"First Line
Second Line
Third Line";
Method 2
string mystring = "First Line \n" +
"Second Line \n" +
"Third Line \n";
Method 3
var mystring = String.Join(
Environment.NewLine,
"First Line",
"Second Line",
"Third Line");
You must make habit to use C# class to generate Html instead concatenation. Please find below code to generate Html using C#.
Check this link for more information
https://dejanstojanovic.net/aspnet/2014/june/generating-html-string-in-c/
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter
Find below code for your question
protected void Page_Load(object sender, EventArgs e)
{
string starOrBullet = "star-link";
string appSet = "http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID=";
string LinkID = "2";
string tabID = "1";
string linkText = "linkText_Here";
string sOutput = string.Empty;
StringBuilder sbControlHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
{
//Generate container div control
HtmlGenericControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("class", string.Format("item link-item {0}",starOrBullet));
//Generate link control
HtmlGenericControl linkControl = new HtmlGenericControl("a");
linkControl.Attributes.Add("href", string.Format("{0}{1}&TabID={2}",appSet,LinkID,tabID));
linkControl.Attributes.Add("target", "_blank");
linkControl.InnerText = linkText;
//Add linkControl to container div
divControl.Controls.Add(linkControl);
//Generate HTML string and dispose object
divControl.RenderControl(htmlWriter);
sbControlHtml.Append(stringWriter.ToString());
divControl.Dispose();
}
}
sOutput = sbControlHtml.ToString();
}

Getting first name on name string with substring fails [C#]

So i have this piece of code:
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
lets suppose the name is "Phiter Fernandes", ok it will say:
Welcome, Phiter!
But if the name is just "Phiter" it will stop and not run the rest of the code.
Obviously is because there are no spaces for the substring method to retrieve the first name.
But i don't want it to skip the rest of the code, i want it to work even if there is no space.
I tried using the try catch, just like this:
try
{
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
}
catch
{
MessageBox.Show("Welcome," + name + "!");
}
It works, but there is an annoying sound when the code runs the catch.
Is there any other way around this? A different way of getting the first name, perhaps?
Try splitting the string wherever there is a space, and selecting the first element, which will always be the first name.
MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");
You can try more than one options.
Replace usign Regex.
string input = "Your string " + "whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
check if space exists.
if(name.Contains(" "))
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
trim spaces
string fullName = name;
var names = fullName.Split(' ');
string firstName = names[0];
MessageBox.Show("Welcome," + firstName + "!");
Let me know which one did you use!

accessing data from database and displaying it in textbox

I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.

Categories