I have a string with special characters insert in different places. For example:
string myString = "This is a textbox: ##";
I would like to replace the ## with a control (namely, a textbox).
The Replace method only allows the string to be replaced with another string or character (understandably). But what would be the best way to dynamically replace the ## with a control in its position?
I was thinking maybe I could replace it with HTML markup which would be executed, but not quite sure how that would be achieved.
Thanks
EDIT: To clarify some details. The strings are being retrieved from a database, so I can't use the PlaceHolder control. The user selects a string from a drop-down list. The value of the item is the string with special characters. When the postback occurs from the item selection, I would like to display the string on the site, but replace the special characters with a fully working control (in this case, a textbox)
Consider leveraging the TextBox's Render() method. That'll get you the HTML that would be output from that TextBox.
You can then use that string to be the replacement text to replace the ## portion of your string.
TextBox Render() on MSDN
var myTxtBox = new TextBox();
myTxtBox.Text = "Hello World";
//implement the Render code in here
string myRenderedTextBoxHTML = RenderIt(myTxtBox);
string myString = "This is a textbox: " + myRenderedTextBoxHTML;
I'm unsure ViewState would be available for this control or not.
Something like this:
Panel panel = new Panel();
string myString = "This is a textbox: ##";
// some parsing logic
string[] arr = { "This is a textBox", "##" };
foreach(var item in arr)
{
if (item == "##"){
TextBox tb = new TextBox();
panel.Controls.Add(tb);
}
else{
Label l = new Label();
l.Text = item;
panel.Controls.Add(l);
}
}
your_plaaceholder.Controls.Add(panel);
myString = string.Replace("##", "<input type='text' />");
Note that this is not a control: it will just be an html element that won't be wired up on the server side later. And depending on what you do with the string maybe not even that much, as some controls (like label) will automatically escape your < and > characters.
If you really want a fully-working asp.net control there we need to know more about how you are adding that string to the page.
You could indeed replace it with markup:
string mystring = "This is a textbox: ##".Replace("##", "<input type='text'/>");
Response.Write(mystring);
I'm not sure why you would want to do this, though. Why not use a PlaceHolder control and just stick a TextBox in it in the code behind?
What Sash said, BUT make sure you put that in the Page.Init() every time if you wish to take advantage of viewstate.
Related
Hello I am new to C Sharp & Windows Forms. I am unable to set the specific string of a multiline TextBox. I have tried below things so far.
textBox1.Lines[1] = "welcome to stackOverflow";
The above code does not give a compile time error but when I saw the result using Debug mode it was not expected.
Then i was also reading this MSDN article but in this there is a new collection created by using stream[] constructor but still the same problem arises.
It should give compiler error because you are trying to assign a string to char here:
textBox1.Text[1] = "welcome to stackOverflow";
Text property is of type string, when you use indexer on a string it gives you the char at that position. And also string is immutable so you can't really change a character at specific position without creating a new string.
You should set the Text directly like this:
textBox1.Text = "welcome to stackOverflow";
Or if you have more than one line in an array of string you should set the Lines property:
var lines = new [] { "foo", "bar" };
textBox1.Lines = lines;
Any value that you set directly to textBox1.Lines will be effected to textBox1.
There is a solution to resolve your problem. I think it's best way.
You have to clone the current value of your textbox. Then you set new value on it. Finally, you set back to textbox.
var curValue = (string[])textBox1.Lines.Clone();
curValue[1] = "welcome to stackOverflow";
//Set back to textBox1
textBox1.Lines = curValue;
I think this should be a pretty easy question to answer but I can't seem to figure it out.
I am adding text to labels from a sqldatasource in c#. All of that works, but I want to be able to format the text. I want to 1) be able to change the format to 0.00 (instead of a string of decimals) and I would also like to be able to add words before the text. I assume I need to somehow use the string.format command but can't figure out how to work it in. Any help would be greatly appreciated. Here's my code below:
DataView dvSql = (DataView)DeskSummary.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drvSql in dvSql)
{
Desk.Text = drvSql["Deskname"].ToString();
MarginLabel.Text = drvSql["margin"].ToString();
CurrentCI.Text = drvSql["comp_index_primarycomp"].ToString();
WalMartCurrentCI.Text = drvSql["comp_index_walmart"].ToString();
ForecastMargin.Text = drvSql["margin_forecast"].ToString();
WalMartForecastCI.Text = drvSql["comp_index_walmart_forecast"].ToString();
ForecastCI.Text = drvSql["comp_index_primarycomp_forecast"].ToString();
}
You can pass the format argument to the ToString() method like so:
MarginLabel.Text = drvSql["margin"].ToString("0.00");
However, as you said you wanted to prepend some text. Therefore, I recommend:
MarginLabel.Text = String.Format("Prepended text {0:0.00}", drvSql["margin"]);
Note: I just picked one of your labels; I'm not sure which ones get special formatting treatment.
use the
string.Format("This is a before text {"0"},your param)
// you can add as many variables and {""} string literals as you need just make sure that you separate the variables with a ","
Here is the code
string stringNumber = "5123.34214513";
decimal decimalNumber = Decimal.Parse(stringNumber);
string output = String.Format("Your text: {0:0.00}", decimalNumber);
Console.WriteLine(output); //Your text: 5123.34
This works if the column is of type string
String.Format() will do what you need for prepending/appending text values,
string.Format("prepend text {"0"} append text", paramString)
But if you want to actually format the value you are getting back from SQL, then you would need to use String.Format() on that value as well as possibly some RegEx expressions and/or .ToUpperCase or .ToLowercase for your capitalization... something like.
var capitalizedString = paramString.subStr(0,1).ToUppercase + paramString.subStr(1, paramstring.Length);
string.Format("Prepended text {"0"} plus appended text", capitalizedString);
I have a field called Description in the front end form, it is a textarea where user can type/copy past the text which include line breaks aswell.
From asp.net all this data goes to sharepoint.
Now I have a search page which returns all these values from sharepoint using webserivices in the format of xml.
The problem is that all of the line breaks in the value in replaced with
I am trying to display the description field values to the label, but its not working I tried below things :
lblDesc.Text = xmlValuesPath.Attribute("ows_Description").Value.Replace("
", "\n");
lblDesc.Text = xmlValuesPath.Attribute("ows_Description").Value.Replace("
", "</p><p>");
The formatting works fine in a textbox, but nothing seems to be working, kindly help.
Did you clear out all HTML tags from it?
public static string ClearHTMLTagsFromString(string htmlString)
{
string regEx = #"\<[^\<\>]*\>";
string tagless = Regex.Replace(htmlString, regEx, string.Empty);
// remove rogue leftovers
tagless = tagless.Replace("<", string.Empty).Replace(">", string.Empty);
tagless = tagless.Replace("Body:", string.Empty);
return tagless;
}
Try to replace "
" with "<br/>" it should work in ASP.NET Label.
By default asp.net coverts it to \n .which at the run time wont be parsed by the html code to you just need to replace \n with ""
xmlValuesPath.Attribute("ows_Description").Value.Replace("\n", "</p><p>")
When I read in the data from SQL it has \r\n for the carriage returns, so I use .Replace to convert the \r\n's to <br/>'s but on display the <br/>'s are ignored. It works if I replace the \r\n's with <p></p> but this is not what I need.
The <br/>'s are being ignored and I need them to produce a newline.
Any insight as to why it is doing this or how to achieve what I am looking to do would be great!
EDIT: I've addressed the typo in the code below - but that isn't my question -at all-. I've asked about BR's and them displaying.
HTML
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
CODE-BEHIND
string strTempDetail = myReader["Detail"].ToString();
string strMoreTempDetail = strTempDetail.Replace("\r\n", "<br/>");
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail.ToString());
PlaceHolder1.Controls.Add(UserControlSpecialOffers);
Thanks!
You have a typo in your code. You are assigning the original string into your control instead of the string containing your replacements.
change
LiteralControl UserControlSpecialOffers = new LiteralControl(strTempDetail.ToString());
to
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail );
Because you're adding strTempDetail to your literal control, not strMoreTempDetail, which is the string where you performed the replacement.
You have the wrong string in this line
LiteralControl UserControlSpecialOffers = new LiteralControl(strTempDetail.ToString());
it should be
LiteralControl UserControlSpecialOffers = new LiteralControl(strMoreTempDetail);
Are you by any change reading your string from SQL Server? If had issues where a string read from an SQL server ntext column contained a '\n' instead of '\r\n' (even though '\r\n' was saved).
Try if string strMoreTempDetail = strTempDetail.Replace("\n", "<br/>") provides better results.
Or to be on the save side, replace both: string strMoreTempDetail = strTempDetail.Replace("\r\n", "<br/>").Replace("\n", "<br/>")
Someone else had modified the css file and put BR display:none; in the CSS. Of all the places!
I have a very simple asp:textbox with the multiline attribute enabled. I then accept just text, with no markup, from the textbox. Is there a common method by which line breaks and returns can be converted to <p> and <br/> tags?
I'm not looking for anything earth shattering, but at the same time I don't just want to do something like:
html.Insert(0, "<p>");
html.Replace(Enviroment.NewLine + Enviroment.NewLine, "</p><p>");
html.Replace(Enviroment.NewLine, "<br/>");
html.Append("</p>");
The above code doesn't work right, as in generating correct html, if there are more than 2 line breaks in a row. Having html like <br/></p><p> is not good; the <br/> can be removed.
I know this is old, but I couldn't find anything better after some searching, so here is what I'm using:
public static string TextToHtml(string text)
{
text = HttpUtility.HtmlEncode(text);
text = text.Replace("\r\n", "\r");
text = text.Replace("\n", "\r");
text = text.Replace("\r", "<br>\r\n");
text = text.Replace(" ", " ");
return text;
}
If you can't use HttpUtility for some reason, then you'll have to do the HTML encoding some other way, and there are lots of minor details to worry about (not just <>&).
HtmlEncode only handles the special characters for you, so after that I convert any combo of carriage-return and/or line-feed to a BR tag, and any double-spaces to a single-space plus a NBSP.
Optionally you could use a PRE tag for the last part, like so:
public static string TextToHtml(string text)
{
text = "<pre>" + HttpUtility.HtmlEncode(text) + "</pre>";
return text;
}
Your other option is to take the text box contents and instead of trying for line a paragraph breaks just put the text between PRE tags. Like this:
<PRE>
Your text from the text box...
and a line after a break...
</PRE>
Depending on exactly what you are doing with the content, my typical recommendation is to ONLY use the <br /> syntax, and not to try and handle paragraphs.
How about throwing it in a <pre> tag. Isn't that what it's there for anyway?
I know this is an old post, but I've recently been in a similar problem using C# with MVC4, so thought I'd share my solution.
We had a description saved in a database. The text was a direct copy/paste from a website, and we wanted to convert it into semantic HTML, using <p> tags. Here is a simplified version of our solution:
string description = getSomeTextFromDatabase();
foreach(var line in description.Split('\n')
{
Console.Write("<p>" + line + "</p>");
}
In our case, to write out a variable, we needed to prefix # before any variable or identifiers, because of the Razor syntax in the ASP.NET MVC framework. However, I've shown this with a Console.Write, but you should be able to figure out how to implement this in your specific project based on this :)
Combining all previous plus considering titles and subtitles within the text comes up with this:
public static string ToHtml(this string text)
{
var sb = new StringBuilder();
var sr = new StringReader(text);
var str = sr.ReadLine();
while (str != null)
{
str = str.TrimEnd();
str.Replace(" ", " ");
if (str.Length > 80)
{
sb.AppendLine($"<p>{str}</p>");
}
else if (str.Length > 0)
{
sb.AppendLine($"{str}</br>");
}
str = sr.ReadLine();
}
return sb.ToString();
}
the snippet could be enhanced by defining rules for short strings
I understand that I was late with the answer for 13 years)
but maybe someone else needs it
sample line 1 \r\n
sample line 2 (last at paragraph) \r\n\r\n [\r\n]+
sample line 3 \r\n
Example code
private static Regex _breakRegex = new("(\r?\n)+");
private static Regex _paragrahBreakRegex = new("(?:\r?\n){2,}");
public static string ConvertTextToHtml(string description) {
string[] descrptionParagraphs = _paragrahBreakRegex.Split(description.Trim());
if (descrptionParagraphs.Length > 0)
{
description = string.Empty;
foreach (string line in descrptionParagraphs)
{
description += $"<p>{line}</p>";
}
}
return _breakRegex.Replace(description, "<br/>");
}