How to remove span when generating HtmlGenericControls from Code Behind - c#

I have this peace of code which generates a dropdown menu, Unfortunately I'm running into issues because span tags are being generated at the creation of each HtmlGenericControl.
This is my code to generate the HtmlGenericControls:
string _touid = Request.QueryString["touid"];
string _group_array = Connections.isp_GET_VALUE("TRSTR", "", "", "");
string _tour_array = _group_array.Replace(" ", "");
HtmlGenericControl _ul = new HtmlGenericControl();
_ul.InnerHtml = "<ul class=\"dropdown-menu\">";
tour_holder.Controls.Add(_ul);
string[] groups = _tour_array.Split(',');
foreach (string group in groups)
{
string _tournoment_string = Connections.isp_GET_VALUE("TRNAM", group, "", "");
HtmlGenericControl _li = new HtmlGenericControl();
_li.InnerHtml = "<li>" + _tournoment_string + "</li>";
tour_holder.Controls.Add(_li);
}
HtmlGenericControl _ul_ = new HtmlGenericControl();
_ul_.InnerHtml = "</ul>";
tour_holder.Controls.Add(_ul_);
Below is the HTML output:
<span><ul class="dropdown-menu"></span>
<span><li>FIFA World Cup Brasil 2014 </li>
</span>
<span><li>FIFA U-20 World Cup New Zealand 2015 </li></span>
<span><li>FIFA Woman's World Cup Canada 2015 </li></span>
<span></ul></span>
</div>
How can I remove the span tag?

A similar question has been asked here.
Try passing the HTML tag the constructor instead of using the InnerHtml property like that:
HtmlGenericControl _ul = new HtmlGenericControl("ul");

Related

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();
}

How to add page no. and print date ms interop word DLL

I want to add following text into MS-Word footer using MS-Interop Word DLL.
Required Footer Text:
"Page 1 of 10 and date = {Current Date}" something like this.
I have added below code which add page no. and current date but its not allowing me add any custom text like "Page 1 of 10".
Here is my code
foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
{
Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
footerRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);
footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldDate,"Date = ");
footerRange.Fields.UpdateSource();
footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage, "Page No = ");
footerRange.Fields.UpdateSource();
footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
}
An idea how to add such functionality?
Here is the solution which I have found.
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
{
Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
footerRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);
footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages);
Microsoft.Office.Interop.Word.Paragraph p4 = footerRange.Paragraphs.Add();
p4.Range.Text = " of ";
footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
Microsoft.Office.Interop.Word.Paragraph p1 = footerRange.Paragraphs.Add();
p1.Range.Text = "Page: ";
footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
Microsoft.Office.Interop.Word.Paragraph p3 = footerRange.Paragraphs.Add();
p3.Range.Text = " " + Environment.NewLine;
footerRange.Fields.Add(footerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldDate);
Microsoft.Office.Interop.Word.Paragraph p2 = footerRange.Paragraphs.Add();
p2.Range.Text = "Print date: ";
footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
}

How to display certain selected words bolder in asp:hyperlink text

I have a asp:repeater control on my .aspx and in the code behind I am binding its datasource to a Collection of type KeyValuePair[]<Literal,String>. I was choosing literal so that I could surround selected words in literal text with <strong> or <b> html tag. Well I succeeded in doing it but I am not finding a way to display the literal text in the asp:hyperlink's Text part of asp:repeater
My .aspx code is as follow:
<asp:Repeater ID="repLinks" runat="server">
<ItemTemplate>
<div onclick="window.open('<%# ((KeyValuePair<Literal,string>)Container.DataItem).Value %>','_blank');">
<div>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# ((KeyValuePair<Literal,string>)Container.DataItem).Value %>" Text="<%#((KeyValuePair<Literal,string>)Container.DataItem).Key.Text %>"
Font-Size='Large' ForeColor='Blue' Font-Names="Open Sans" CssClass="linkstyle" />
<br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I need help on how to display the .Key.Text part in asp:Hyperlink.
I added the keyValuePair as follow:
char[] seperator = { ' ' };
String[] explodedString = Results1[index].Key.Split(seperator);
List<String> Query= new List<string>(TextBox1.Text.Trim().ToLowerInvariant().Split(seperator,StringSplitOptions.RemoveEmptyEntries));
for (int i = 0; i < explodedString.Length; i++)
{
if (Query.Contains(explodedString[i].ToLowerInvariant()) == true)
{
explodedString[i] = "<strong>" + explodedString[i] + "<strong>";
}
}
Literal temp = new Literal();
temp.Text = explodedString.ToString();
TryCurrentWindow[index] = new KeyValuePair<Literal, string>(temp, Results1[index].Value);
Here TryCurrentWindow is the KeyValuePair[] and explodedstring[] is the text string splitted by '' char which I want to modify and Query[] is list of my keyWords
Problem:
You are not closing <strong> tag like this </strong>.
You are simply doing ToString() to string[] array.
Updated this line:
explodedString[i] = "<strong>" + explodedString[i] + "</strong>";
Also change below code:
Literal temp = new Literal();
temp.Text = explodedString.ToString();
With this:
Literal temp = new Literal();
temp.Text = string.Join(" ", explodedString);
As indexes are modified in the string[] array. You are required to join array to get modified string[] array.
Updated Code Snippet:
char[] seperator = { ' ' };
String[] explodedString = Results1[index].Key.Split(seperator);
List<String> Query= new List<string>(TextBox1.Text.Trim().ToLowerInvariant().Split(seperator,StringSplitOptions.RemoveEmptyEntries));
for (int i = 0; i < explodedString.Length; i++)
{
if (Query.Contains(explodedString[i].ToLowerInvariant()) == true)
{
explodedString[i] = "<strong>" + explodedString[i] + "</strong>"; //changed
}
}
Literal temp = new Literal();
temp.Text = string.Join(" ", explodedString); //changed
TryCurrentWindow[index] = new KeyValuePair<Literal, string>(temp, Results1[index].Value);

Html Agility Pack foreach loop error

string searchString = textBox1.Text.Replace(" ", "%20");
string url = "http://sometorrentsearchurl.com/search/" + searchString + "/0/99/401";
HttpWebRequest oReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)oReq.GetResponse();
var doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(resp.GetResponseStream());
foreach (HtmlNode torrent in doc.DocumentNode.SelectNodes("//tr"))
{
foreach (HtmlNode title in torrent.SelectNodes(".//a[#class='detLink']"))
{
Label tTitle = new Label();
tTitle.Text = title.InnerText;
tTitle.Location = new Point(133, tHeightLoc);
tTitle.BackColor = Color.Transparent;
tTitle.ForeColor = Color.White;
tTitle.AutoSize = false;
tTitle.Font = new Font("Arial", 10);
tTitle.Size = new Size(347, 25);
tTitle.TextAlign = ContentAlignment.MiddleLeft;
tTitle.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right);
panel2.Controls.Add(tTitle);
tHeightLoc += 45;
}
}
I am trying to get the list of torrents from a site and for every html th tag found I want to create some controls in my form with values taken from other children html tags, but this line returns an error foreach (HtmlNode title in torrent.SelectNodes(".//a[#class='detLink']"))
I want to know how to fix it because is the first time that I am using Html Agility Pack.
The problem was here torrent.SelectNodes(".//a[#class='detLink']")), it was a null selection an I fixed it like this torrent.SelectNodes("//a[#class='detLink']"))

Asp.net control to HTML

I'm just trying to get the equivalent HTML code that represent a specific control in asp.
for example i have the following label in ASP
Label x=new Label();
x.ID="a123";
x.Text="b123";
i just want to find a way to get
"<span id='a123'>b123</span>"
You can use this method to render controls to html.
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
And use
Label x = new Label();
x.ID = "a123";
x.Text = "b123";
var html = RenderControl(x);
will give you <span id="a123">b123</span>

Categories