find a control with no runat='server' from server side - c#

my code :
<div id="conversationdiv" runat="server">
<table border="1" id="table_id">
<tr>
<td>blah blah</td>
</tr>
</table>
</div>
<asp:button id='clickMe' runat='server' onClick="Click_me" Text="appendRow"></asp:Button>
ServerSIde:
protected void Click_me(object sender,EventArgs e){
HtmlTable table = (HtmlTable)ConversationDIv.FindControl("table_id");
}
the HtmlTable table return null and i know it's because there is no runat='server' attribute for the table, but my question is there a way that can I still find the table even if no such attribute added ?

You could do conversationdiv.InnerHtml... in this specific case it would return the HTML of the table.
You could then use HTML Agility Pack to query or manipulate the said table.
Example
var html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(conversationdiv.InnerHtml);
var table = html.DocumentNode.SelectNodes("table").FirstOrDefault();
var tr = table.SelectNodes("tr").FirstOrDefault();
var td = tr.SelectNodes("td").FirstOrDefault();
var blahBlah = td.InnerText;

Related

Get specific table from html document with HtmlAgilityPack C#

I have html document with two tables. For example:
<html>
<body>
<p>This is where first table starts</p>
<table>
<tr>
<th>head</th>
<th>head1</th>
</tr>
<tr>
<td>data</td>
<td>data1</td>
</tr>
</table>
<p>This is where second table starts</p>
<table>
<tr>
<th>head</th>
<th>head1</th>
</tr>
<tr>
<td>data</td>
<td>data1</td>
</tr>
</table>
</body>
</html>
And i want to parse first and second but separatly
I will explain:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(#richTextBox1.Text);
if(comboBox_tables.Text.Equals("Table1"))
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("inserted_at", typeof(string));
dt.Columns.Add("DisplayName", typeof(string));
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in doc.DocumentNode.SelectNodes("//tr"))
{
var nodes = row.SelectNodes("td");
if (nodes != null)
{
var id = nodes[0].InnerText;
var inserted_at = nodes[1].InnerText;
var DisplayName = nodes[2].InnerText;
dt.Rows.Add(id, inserted_at, DisplayName);
}
dataGridView1.DataSource = dt;
I'm trying to select first table with //table[1]. But it's always takes both tables. How can i select the first table for if(table1) and the second for else if(table2)?
You are selecting the table[1], but not doing anything with the return value.
Use the table variable to select all tr nodes.
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in table.SelectNodes("//tr"))
.. rest of the code

Set innerHTML value to a div element from code behind using a string as the div ID

I am using the below code in my .aspx page.
<form runat="server">
<div style="background:#ffffff;height:1150px;width:100%">
<center>
<table class="calendar-table" cellpadding="0" cellspacing="2" border="1">
<tr>
<td>
<div class="cell">
<div class="cell-day">
<asp:Label ID="label_day_11" runat="server" Text=""></asp:Label>
</div>
<div id="event_11" runat="server">
</div>
</div>
</td>
</tr>
<table>
</center>
</div>
</form>
In my original code I will have a total of 6 rows and 7 columns and the label rows and columns will go from 11 till 67 in the form of a matrix. Here I would like to set the value of label_day_11 from code behind using C# and for that I am using the below code,
int i = 1; // 1 till 6 rows
int j = 1; // 1 till 7 columns
string dayId = "label_day_" + i.ToString() + j.ToString();
Label day = FindControl(dayId) as Label;
day.Text = "Monday";
The above code works fine. But now I want to assign a innerHTML value to the event_11 div element also. But I am not sure how to get that ID and how to set the innerHTML. Is there any way to access the div control using a string in C# and then set a innerHTML value to it? In case of a asp:Label I used the control value as Label but not sure how to get the control of a normal html div element.
I tried the below code but it does not work for me.
string eventId = "event_" + i.ToString() + j.ToString();
Control div = FindControl(eventId);
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
div.RenderControl(w);
I am not sure how to proceed using this. Any solutions?
I think it should work if you cast it to HtmlGenericControl.
HtmlGenericControl div = FindControl(eventId) as HtmlGenericControl;
div.InnerHtml = "your inner html";
https://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol(v=vs.110).aspx

how to use ul and li in code behind c#

I am trying to fill li and ul of an HTML file using my database.
single category representing multiple items in database.
I have taken the li items in a string, I am replacing [food] with CATEGORY name and [itemTemplate] with ITEMS. The issue in my code is the category name is repeating
Every time as new item display. I have to show category name once and add all related items within that category.
String liTemplate = "<li><h4 class='menu-title-section'> <h4 class='menu-title-section'><a href='#appetizers'>[food]</a></h4>[itemTemplate]</li>";
String itemTemplate = "SOME ITEM TEMPLETE";
DataTable dt = dm.GetData("spTestMenu")
StringBuilder sb = new StringBuilder();
sb.Append("<ul class='our-menu'>");
String liTemplateWorkingCopy = String.Empty, itemTemplateWorkingCopy = String.Empty
foreach (DataRow level1DataRow in dt.Rows)
{
liTemplateWorkingCopy = liTemplate;
itemTemplateWorkingCopy = itemTemplate;
SubCategoryName = level1DataRow["MealSubCatName"].ToString();
if (!previusSubCat.Equals(SubCategoryName))
{
liTemplateWorkingCopy = liTemplateWorkingCopy.Replace("[food]", level1DataRow["MealSubCatName"].ToString());
previusSubCat = SubCategoryName;
}
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[foodtitle]", level1DataRow["itemName"].ToString());
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[imgsrc]", level1DataRow["imageURL"].ToString());
itemTemplateWorkingCopy = itemTemplateWorkingCopy.Replace("[price]", level1DataRow["Price"].ToString());
liTemplateWorkingCopy = liTemplateWorkingCopy.Replace("[itemTemplate]", itemTemplateWorkingCopy);
sb.Append(liTemplateWorkingCopy);
foodMenu.Text = sb.ToString();
}
You can set runat="server" for <li> or <ul>..
<li class="abc" runat="server" id="first"></li>
I would suggest using a ListView control for this. This way you can maintain the HTML outside of your code; it's cleaner that way and much more elegant.
Group your rows by the 'MealSubCatName' column, and use LINQ to create an anonymous object:
C#
var grouped = dt.AsEnumerable().GroupBy(c => c["MealSubCatName"].ToString())
.Select(g => new
{
category = g.FirstOrDefault()["MealSubCatName"].ToString(),
items = g.Select(r => new {
title = r["itemName"].ToString(),
image = r["imageURL"].ToString()
})
});
lvFood.DataSource = grouped;
lvFood.DataBind();
ASPX
<asp:ListView ID="lvFood" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder runat="server" ID="groupPlaceholder" />
</ul>
</LayoutTemplate>
<GroupTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</GroupTemplate>
<ItemTemplate>
<li>
<h4 class="menu-title-section">
<%# Eval("category") %>
</h4>
</li>
<asp:Repeater ID="rpt" runat="server" DataSource='<%# Eval("items") %>'>
<ItemTemplate>
<img src="<%# Eval("image")%>" alt="<%# Eval("title")%>" />
<strong><%# Eval("title")%></strong><br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:ListView>
Add a div with runat server and assign a Id to that div and do something like this I did this trick here www.journeycook.com Check menu of this website.
Suppose you have a div with id link and runat server in ul tag
<ul>
<div runat="server" id="link">
</div>
</ul>
Now add c# code for fetch data using SqlDataReader class and using while loop do something like this
link.innerhtml+="<li>dr["yourcolumn"].ToString()</li>";
I hope it will give you some help

Storing the data of Html Table while button click event fired

I am stuck in a situation, web site is running in ASP.NET 1.1
I am loading a page with some data. In the page there is a Html Table.
In each row, I am loading status(active/inactive) in one and message in another .
There is a save button when clicked it should save the status and message to database.
Since the data is in Html Table I am loosing the data while button is clicked.
I tried one option of keeping the status and message at page load in a global Javascript variable. But I will loose that also when button is clicked.
JS Code to store the data :
// To store all active or inactive feature values.
var arrType = [];
var interiorValues = [arrType];
var exteriorValues = [];
var mechanicalValues = [];
var standardValues = [];
function StoreChromeVallue()
{
var $jDecode = jQuery.noConflict();
var table = document.getElementById('dlInterior');
for (var i = 1, row; row = table.rows[i]; i++)
{
for (var j = 0, col; col = row.cells[j]; j++)
{
var imagePath = $jDecode(row.cells[0]).find('img:first').attr('src');
if(imagePath == "../icon_active1.gif")
{
arrType.push("active");
}
else if(imagePath == "../icon_deleted1.gif")
{
arrType.push("deleted");
}
else
{
arrType.push("active");
}
var featureValue = $jDecode(row.cells[1]).text();
arrType.push(featureValue);
arrType.push("Interior");
interiorValues.push(arrType);
}
}
alert(interiorValues[5][0]);
}
HTML TABLE WHERE DATA IS STORE
<TABLE id="dlInteriors" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="interiortd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
Rows are dynamically added on page load.
Please guide me how I should go ahead on this.
You cant easily get all the values/strings in your HTML page while postback. You could able to get the form fields like input, select, etc in post back using Request.params[""].
But you could try with hidden variable (here it is your alternative Viewstate for your HTML table string values)
When & What you store / how to store /how to access in post back.
You can try the below steps for above question.
Before submit a form, fire a javascript function 'saveTableValues()'
which loops your HTML table and creates the object (var) for each row.
Prepare a javascript object array (just pushing the item in for each loop)
Convert it into JSON string and assign the whole JSON string
into Hidden Field
Do post back // just return true in JS
In code behind try accessing using Request.Params[""] or
normal way like hdnField.Text if it is server side control
In Code behing use a JavaScript Serializer
or JSON.Net to convert the JSON string into some collection.
Recommending JSON.Net here
This may help you.!
Edit:
As your website is running in 1.1 not sure those serializer dll will help you. So you try in XML format instead of JSON. Not sure JSON serializer dll is exist for 1.1 framework
Create table to run at server like this
<table id="users" runat="server">
and you will be able to access it using HtmlTable class,If required create a DataTable dynamically from the table rows and save that in a session. Have a look at http://msdn.microsoft.com/en-us/li
Use Jquery to get the rows values. Then store the data into hiddenfields. This way:
<script type="text/javascript">
function getTableValues() {
var tds = $('#dlInteriors tr td')
jQuery.each(tds, function () {
var url = $(this).children('img:first').attr('src');
var text = $(this).text();
if (url)
$('#hidValuesStatus').val($('#hidValuesStatus').val() + ',' + url);
if (text)
$('#hidValuesMessages').val($('#hidValuesMessages').val() + ',' + text);
});
}
</script>
Call the javascript function on the event "OnClientClick" of your asp:button
<TABLE id="dlInteriors" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="interiortd" vAlign="top" width="350" runat="server"><img src="icon_active1.gif" /></TD>
<TD id="TD2" vAlign="top" width="350" runat="server">message1</TD>
</TR>
<TR>
<TD id="TD1" vAlign="top" width="350" runat="server"><img src="icon_deleted1.gif" /></TD>
<TD id="TD3" vAlign="top" width="350" runat="server">message2</TD>
</TR>
</TABLE>
<asp:Button runat="server" ID="btnSubmit" OnClientClick="javascript:getTableValues()" Text="SUBMIT" />
<input type="hidden" id="hidValuesMessages" runat="server" />
<input type="hidden" id="hidValuesStatus" runat="server"/>
And in the code behind get the data from the hidden fields:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then
If Not IsNothing(Request.Form("hidValuesMessages")) Then
Dim str As String = Request("hidValuesMessages")
End If
If Not IsNothing(Request.Form("hidValuesStatus")) Then
Dim str2 As String = Request("hidValuesStatus")
End If
End If
End Sub
Split the string and get the final values.
Hope this helps!
Regards.

How to add text to span control dynamically in c#

net c#. I am using a place holder, and adding span dynamically to the place holder. How can i add text to span dynamically in c# asp.net?
you can use html generic control it would be somethink like this
var yourspan = new HtmlGenericControl("span");
span.InnerHtml = "the text inside your span ";
yourspan.Attributes["id"] = "yourspan";
pannel.Controls.Add(span);
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx
Make Table runat="server"
<table id="myTable" runat="server" width="100%">
<tr>
<td>
<span></span>
</td>
</tr>
</table>
**In code behind u do like this**
myTable.Rows[1].Cells[0].InnerHtml = "<span id="1">" + YOURTEXT+ "</span>";

Categories