How to replace row id with array string at runtime? - c#

Design Code
<tr id="DEPB" runat="server"></tr>
<tr id="DEPB" runat="server"></tr>
<tr id="DEPB" runat="server"></tr>
Behind Code
string Test = ddlExim.SelectedItem.Text.Substring(3);
txtEximDesc.Text = ddlExim.SelectedItem.Text.Substring(3);
string[] Demo = ddlExim.SelectedValue.Split(',');
try
{
DBK.Style.Add("display", "none");
DEPB.Style.Add("display", "none");
EPCG.Style.Add("display", "none");
NFEI.Style.Add("display", "none");
for (int i = 0; i < 3; i++)
{
if (Demo[i] == "DEPB")
{
Demo[i].Style.Add("display", "table-row");
}
else if (Demo[i] == "EPCG")
{
EPCG.Style.Add("display", "table-row");
}
else if (Demo[i] == "DBK")
{
DBK.Style.Add("display", "table-row");
}
else if (Demo[i] == ".")
{
NFEI.Style.Add("display", "table-row");
}
}
}
catch (Exception ex)
{
string Message = ex.Message;
}
i want to replace DEPB,EPCG,DBK with Demo[i] like below but getting error: "String doesnt contain a defnition for style".
Demo[i].Style.Add("display", "table-row");

Mark runat="server" to the table element inside which these tablerows are present ("tbl" in my example) and then try the following code.
for (int i = 0; i < Demo.Length; i++)
{
(tbl.FindControl(Demo[i]) as HtmlTableRow).Style.Add("display", "table-row");
}
Of course you need to add the following namespace.
using System.Web.UI.HtmlControls;
Hope this helps.

Demo is an array of string, hence Demo[i] is a string and string doesn't have property Style. This line look like an outlier compared to other if's content :
Demo[i].Style.Add("display", "table-row");
I guess it should be as follow instead :
DEPB.Style.Add("display", "table-row");

Try to cat Demo[i] to webcontrol

Related

How to load a csv file as Json data in a MVC web application. Header can be different

I'm trying to read a csv file so that I can load a jQuery DataTable. The csv file might have different headers. I was using the header to create the columns for the jQuery table. Then loading the file in and creating the rows. I was doing this directly from the csv file and all worked okay, but only if the file was small. I needed to move to using Json in order to implement a way using Linq to sort, filter, and query in the Model portion of the code. While trying to move to an MVC model, I got into a position where I can't extract the rows from the Json data.
Here is the ViewFile, which currently has the LoadDataAsJson (which should be in the Model class, I'll bet). The Json it creates is correct.
public IActionResult ViewFile()
{
string fileName = Request.Form["fileName"];
ViewData["name"] = fileName;
ViewData["data"] = LoadDataAsJson(dir + Path.DirectorySeparatorChar + fileName, 100);
return View();
}
private string LoadDataAsJson(string fileName, int limit)
{
string[] headers = new string[8];
StringBuilder bldr = new StringBuilder();
bldr.Append("[");
using (TextReader reader = new StreamReader(fileName))
{
String line = null;
int k = 0;
while ((line = reader.ReadLine()) != null)
{
if (k > limit)
break;
if (k++ != 0)
{
if (k != 2)
bldr.Append(","); // append a comma to the end of previous line
List<string> aRow = FormatAsJsonArray(line);
bldr.AppendLine();
bldr.Append("{");
for (int i = 0; i < headers.Length; i++)
{
bldr.Append(headers[i]);
bldr.Append(":\"");
bldr.Append(aRow[i]);
bldr.Append("\"");
if (i != headers.Length - 1)
bldr.Append(",");
}
bldr.Append("}");
}
else
{
headers = line.Split(',');
}
}
}
bldr.Append(Environment.NewLine + "]" + Environment.NewLine);
return bldr.ToString();
}
private List<string> FormatAsJsonArray(string aLine)
{
int k = 0;
string[] tokens = aLine.Split(',');
List<string> items = new List<string>();
string lastPart = "";
if (tokens.Length > 6)
{
for (int i = 7; i < tokens.Length; i++)
{
lastPart = String.Concat(lastPart, tokens[i]);
if (i != tokens.Length - 1)
lastPart += ",";
}
}
for (int i = 0; i < tokens.Length; i++)
{
if (i > 8)
break;
if (tokens[i].Contains("["))
{
List<string> msecs = MsecColumnAsJson(tokens[i]);
for (int kk = 0; kk < msecs.Count; kk++)
items.Add(msecs[kk]);
}
else if (k < 7)
items.Add(tokens[i]);
k++;
}
if (lastPart != null && lastPart.Length > 0)
items.Add(lastPart);
return items;
}
The ViewFile.cshtml contains in part.
<h2>#ViewData["name"]</h2>
<div class="container">
<br />
<table id="table_id" class="table table-condensed table-striped table-hover display">
<thead>
<tr>
<th>DateTime</th>
<th>Msecs</th>
<th>Thread</th>
<th>Level</th>
<th>Logger</th>
<th>Host</th>
<th>Msg Type</th>
<th>Message</th>
</tr>
</thead>
<tbody>
#{
string logFile = (string)#ViewData["data"];
var k = 0;
}
#foreach (string lf logFile)
{
if (k++ > 50)
{
break;
}
<tr>
#foreach (string item in lf)
{
<td>
#item
</td>
}
</tr>
}
</tbody>
</table>
</div>
I end up getting cannot convert type 'char' to 'string' in each of the foreach statements. I tried using var for the var logFile = #ViewData["data"] line, but then the rest isn't working.
My intention was to extract on Json array line at a time, then break each of those up into a single td. How can I use the LogFileModel to contain the handling of the data, and create a view and controller to do this?
I would suggest going a different approach.
Use TextFieldParser from Microsoft.VisualBasic.FileIO (Yes, you can use that in C#) to read CSV and place it as data model and then use Newtonsoft.Json to create json from that objects.
Here's more on TextFieldParser: https://coding.abel.nu/2012/06/built-in-net-csv-parser/

using c# remove duplicate html span elements

I have to convert word to html which I'm doing with Aspose and that is working well. The problem is that it is producing some redundant elements which I think is due to the way the text is store in word.
For example in my word document the text below appears:
AUTHORIZATION FOR RELEASE
When converted to html it becomes:
<span style="font-size:9pt">A</span>
<span style="font-size:9pt">UTHORIZATION FOR R</span>
<span style="font-size:9pt">ELEASE</span>
I'm using C# and would like a way to remove the redundant span elements. I'm thinking either AngleSharp or html-agility-pack should be able to do this but I'm not sure this is the best way?
What I wound up doing is iterating over all the elements and when adjacent span elements were detected I concatenated the text together. Here is some code if others run into this issue. Note code could use some cleanup.
static void CombineRedundantSpans(IElement parent)
{
if (parent != null)
{
if (parent.Children.Length > 1)
{
var children = parent.Children.ToArray();
var previousSibling = children[0];
for (int i = 1; i < children.Length; i++)
{
var current = children[i];
if (previousSibling is IHtmlSpanElement && current is IHtmlSpanElement)
{
if (IsSpanMatch((IHtmlSpanElement)previousSibling, (IHtmlSpanElement)current))
{
previousSibling.TextContent = previousSibling.TextContent + current.TextContent;
current.Remove();
}
else
previousSibling = current;
}
else
previousSibling = current;
}
}
foreach(var child in parent.Children)
{
CombineRedundantSpans(child);
}
}
}
static bool IsSpanMatch(IHtmlSpanElement first, IHtmlSpanElement second)
{
if (first.ChildElementCount < 2 && first.Attributes.Length == second.Attributes.Length)
{
foreach (var a in first.Attributes)
{
if (second.Attributes.Count(t => t.Equals(a)) == 0)
{
return false;
}
}
return true;
}
return false;
}

Check if Cell is empty to break while loop

Hello I work on a method to extract data from Cells. This works but every time I reach an empty cell I get a NullBinderException.
My question is how can I prevent this?
Here is the part that makes problems:
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
Stuff that I tried:
range.Offset = Cant use becouse this is not an aviable Member.
IsNullOrEmpty = Makes no difference
So there is something I don't get. Any help or advise would be great and thanks for your time.
The Cell Range and/or Value2 may be null. Check these within your Where clause.
while ((range.Cells[startpoint, cell] as Excel.Range) != null && (range.Cells[startpoint, cell] as Excel.Range).Value2 != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
You can make your while loop as:-
while (! IsNull(range.Cells[startpoint, cell] as Excel.Range).Value2))
You could try catch you exception like:
try
{
while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
{
for (int i = 1; i <= numberOfColumns; i++)
{
string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
stringList.Add(sValue);
cell++;
}
startpoint++;
cell = 1;
}
}
catch(nullBinderException e)
{
//you find an empty cell
//... break? jump over and continue?
//... your logic...
}

razor syntax to write tags based on the condistion

#for (var i = 0; i < 3; i++)
{
if(#Model.lstEmp[i].isTrue==true)
{
<tr bgcolor="red">
}
else
{
<tr>
}
<td>#Model.lstDept[i].DeptId</td>
<td>#Model.lstEmp[i].EmpId</td>
</tr>
}
I am facing an error message that '}' not found. when I write everything inside the if and else block I'm not facing any issue but if I write like above I'm facing the issue. please help me in solving this.
Try the following:
#for (var i = 0; i < 3; i++)
{
if(#Model.lstEmp[i].isTrue==true)
{
#:<tr bgcolor="red">
}
else
{
#:<tr>
}
#:<td>#Model.lstDept[i].DeptId</td>
#:<td>#Model.lstEmp[i].EmpId</td>
#:</tr>
}
I think the only problem is that you have if(#Model). You don't need the # there because it is still in the razor context. Somehow it knows whether or not to interpret it as c# or html (not always perfect).
#for (var i = 0; i < 3; i++)
{
if(Model.lstEmp[i].isTrue==true)
{
<tr bgcolor="red">
}
else
{
<tr>
}
<td>#Model.lstDept[i].DeptId</td>
<td>#Model.lstEmp[i].EmpId</td>
</tr>
}

How can I loop through table rows to toggle the display style?

I would like to toggle the display row for a table in javascript. How do I do this?
<script type="text/javascript" language="javascript">
function vehicleSelected() {
var autoSelect = document.getElementById('vehicleSelect');
var strAuto = autoSelect.options[autoSelect.selectedIndex].value;
var rowAuto = document.getElementById(strAuto);
for (var i = 4; i < tableList.rows.length; i++) {
//I am not sure how to access the id for comparison to rowAuto
if (//table row == strAuto) {
rowAuto.style.display = '';
} else {
rowAuto.style.display = 'none';
}
}
}
</script>
<table id="tableList">
<tr id="optionA"><td>Display Row A</td></tr>
<tr id="optionB"><td>Display Row B</td></tr>
<tr id="optionC"><td>Display Row C</td></tr>
<tr id="optionD"><td>Display Row D</td></tr>
</table>
First, consider jquery. It's a big help for things like this.
Second, if you're not going to use jquery, then what you want to do is something like this:
function vehicleSelected() {
var autoSelect = document.getElementById('vehicleSelect');
var strAuto = autoSelect.options[autoSelect.selectedIndex].value;
var rows = document.getElementById('tableList').getElementsByClassName('TR');
for (var i = 0; i < rows.length; i++) {
rows[i].style.display='none'; // note: better to use a css class here
}
var selectedRow = document.getElementById(strAuto); // assuming that the values are the same as the row Id's.
selectedRow.style.display = ''; // again, better to use a Css style.
}
You could do it easily with jQuery:
function vehicleSelected() {
var autoSelect = //...
var strAuto = //...
$("#tableList tr").hide().filter("#" + strAuto).show();
}
If I correctry understood you, this should help you.
var table = document.getElementById('tableList');
for(var i=0; i<table.rows.length; i++){
if (table.rows[i].attributes["id"].nodeValue == strAuto) {
table.rows[i].style.display = '';
} else {
table.rows[i].style.display = 'none';
}
}

Categories

Resources