Building an string named html in the aspx.CS page using C# language.
Assuming DataTable dt.
This obviously doesn't work:
string html = "dt["FirstName"]";
Neither does this:
string html = "dt[\"FirstName\"]";
Neither does this:
string html = ""+dt+"[\"FirstName\"]";
Full Code (was really just trying to keep this question simple, but this might help for understanding):
public static string ConvertDataTableToHtmlTable(DataTable dt)
{
string html = "<h3>Locations:</h3><table class=\"table table-condensed\" style=\"border-collapse:collapse;\">";
//add header row
html += "<thead><tr><th> </th><th>City</th><th>Contact</th><th>Stations</th></tr></thead><tbody>";
int i = 1;
//add rows
foreach (DataRow row in dt.Rows)
{
//visible row
html += "<tr data-toggle=\"collapse\" data-target=\"#demo"+i+"\" class=\"accordion-toggle\">";
html += "<td><button class=\"btn btn-default btn-xs\" onclick=\"return false;\"><span class=\"glyphicon glyphicon-option-horizontal\"></span></button></td>";
html += "<td>"+dt[\"CompanyCity\"]+</td>";
html += "<td>"+dt[\"FirstName\"]+</td>";
html += "<td> 11 </td></tr>";
//collapsable row
html += "<tr><td colspan = \"12\" class=\"hiddenRow\"><div class=\"accordian-body collapse\" id=\"demo"+i+"\">";
html += "<table class=\"table table-striped\"><thead>";
html += "<tr><th>License Key</th><th>Start</th><th>Expire</th><th>Product</th><th>Version</th><th>Level</th><th>Model</th><th>User</th><th>Email</th></tr></thead><tbody>";
html += "<tr><td>Instalcode </td><td> start </td><td> expire </td><td> product </td><td> version </td><td> level </td><td> model </td><td> user </td><td> email </td></tr>";
html += "</tbody></table></div></td></tr>";
i++;
}
html += "</tbody></table>";
return html;
}
Page load (dtActive is the datatable with data)
protected void Page_Load(object sender, EventArgs e)
{
locationsTable.InnerHtml = ConvertDataTableToHtmlTable(dtActive);
}
ASPX Page:
<div id="locationsTable" runat="server"></div>
Any help is appreciated and of course if you need me to be more specific, or if this is a duplicate please comment below with your request/link. Thank you
You need to iterate through the records of the datatable
foreach (DataRow dr in dt)
{
String firstname = dr["FirstName"] != null ? dr["FirstName"].ToString() : string.Empty;
}
edit
Based on your editing:
You're iterating but using the wrong reference, use row["FirstName"] instead of dt["FirstName"]
Related
I have a GridView on a page. The user is able to input data in that GridView then I am downloading an Word file on Submit Event.
Now the question is: How can I download specific Column data to that word file? That word file also contains other data from different fields from same the page, which are working fine.
Below is the code for GridView: (Grid is binding on page load)
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridViewData11.Rows[rowIndex].Cells[1].FindControl("Data1");
TextBox box2 = (TextBox)GridViewData11.Rows[rowIndex].Cells[2].FindControl("Data2");
TextBox box3 = (TextBox)GridViewData11.Rows[rowIndex].Cells[3].FindControl("Data3");
TextBox box4 = (TextBox)GridViewData11.Rows[rowIndex].Cells[4].FindControl("Data4");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
box4.Text = dt.Rows[i]["Column4"].ToString();
rowIndex++;
}
}
Below code is for Download data to Word file:
public void GenerateWordDoc()
{
string strBody = "<html>" +
"<body>" +
"<div> <b> Details </b></div> <br>" +
"<table MAX width=\"701\" height=\"646\" border=\"1\"> <tr><td width=\"191\" height=\"26\" >Name of user </td> <td height=\"86\" > Comments</td><td colspan=\"3\"> </td></tr> </table>" +
"</body>" +
"</html>";
string fileName = “wordfile.doc”;
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Write(strBody);
}
I've just started playing with developing in SP2010, so I'm complete begginer .
I've created simple console application with code like this :
using (SPSite currentSite = new SPSite("http://win-e9840laitme"))
{
using (SPWeb currentWeb = currentSite.OpenWeb())
{
SPList myList = currentWeb.Lists["List1"];
string currentUserName = currentWeb.CurrentUser.Name;
SPQuery queryInformationAboutCurrentUser = new SPQuery();
queryInformationAboutCurrentUser.Query = "<Where>" +
"<Eq><FieldRef Name='EmployeeName'/><Value Type='Text'>" + currentUserName + "</Value></Eq>" +
"</Where>";
List<EmployeeInfo> listEmployeeInfo = new List<EmployeeInfo>();
SPListItemCollection collectionEmployee = myList.GetItems(queryInformationAboutCurrentUser);
foreach (SPListItem info in collectionEmployee)
{
EmployeeInfo eInfo = new EmployeeInfo();
eInfo.Deparment = info["Office"].ToString();
listEmployeeInfo.Add(eInfo);
}
foreach (EmployeeInfo eI in listEmployeeInfo)
{
SPQuery querySameOffice = new SPQuery();
querySameOffice.Query = "<Where>" +
"<Eq><FieldRef Name='Office'/><Value Type='Choice'>" + eI.Deparment + "</Value></Eq>" +
"</Where>";
SPListItemCollection collectionEmployeeDisplay = myList.GetItems(querySameOffice);
foreach (SPListItem item in collectionEmployeeDisplay)
{
Console.WriteLine(item["EmployeeName"].ToString() + " " + item["PhoneNumber"].ToString() + "\n");
}
}
}
}
Now I want to use that code inside sharepoint project , and instead of putting result of SPQuery on Console , I want to populate HTML table with the result staticly(without JS or Jquery , if it is possible).
I've created sp project and added ApplicationPage.
My idea was to use StringBuilder and something like this :
StringBuilder html = new StringBuilder();
html.Append("<table border = '1'>");
//Building the Header row.
html.Append("<tr>");
html.Append("<th>");
html.Append("EmployeeName");
html.Append("</th>");
html.Append("<th>");
html.Append("PhoneNumber");
html.Append("</th>");
html.Append("</tr>");
and in the last foreach loop this code :
foreach (SPListItem item in collectionEmployeeDisplay)
{
html.Append("<tr>");
html.Append("<td>");
html.Append(item["EmployeeName"].ToString());
html.Append("</td>");
html.Append("<td>");
html.Append(item["PhoneBook"].ToString());
html.Append("</td>");
html.Append("</tr>");
}
//Table end.
html.Append("</table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
I beleive there are more elegant solutions to this problem, and if you now it please give me idea .Thank you.
I've found a solution.First we need to add Repeater into PlaceHolderMain :
<asp:Repeater ID="rptEmployees" runat="server">
<HeaderTemplate>
<table border="1" style="width:70%">
<tr>
<td>Employee Name</td>
<td>Phone Number</td>
<td>Position</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("EmployeeName") %></td>
<td><%# Eval("PhoneNumber") %></td>
<td><%# Eval("Position") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
than create another class and add this code into final loop:
foreach (SPListItem item in collectionEmployeeDisplay)
{
DisplayEmployee dE = new DisplayEmployee();
dE.EmployeeName = item[Sol.PB1.Fields.EmployeeName].ToString();
dE.PhoneNumber = item[Sol.PB1.Fields.PhoneNumber].ToString();
dE.Position = item[Sol.PB1.Fields.Position].ToString();
display.Add(dE);
}
rptEmployees.DataSource = display;
rptEmployees.DataBind();
}
You cant use XSLT transformation to convert your SPQuery results to an HTML table. see example of Applying an XSLT Transform to a DataSet
I am concatenating my HTML in string now the HTML coming from my DB
also there some images stores in DB Both path and Bytes...
now i want to show my image in html <img> tag then i write it on doc file
Here is my code:
if (ds.Tables[4].Rows.Count > 0)
{
DataTable Dt_4 = ds.Tables[4];
foreach (DataRow item in Dt_4.Rows)
{
QuestionName += "<br style='page-break-before: always'> <br style='page-break-before: always'>";
QuestionName += "<b><span style='text-decoration:underline'>Question : </span>" + Dt_4.Rows[0]["Q_Num"].ToString() + "</b>";
QuestionName += "<b><span style='padding-left:20px;'>Marks : </span>(" + item["Marks"].ToString() + ")</b>";
QuestionName += item["QuestionName"].ToString();
string imagePath = item["ImagePath"].ToString();
QuestionName += " <div><img src='" + imagePath + "' height='350' width='450'> </div> ";
}
}
the image shows correctly when i run it on sever but when i access server from my local machine it doesn't show
any help ???
You can embed the images as Base64 encodes string, like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
gCAQBVDLuv+V20dE....." alt="beastie.png">
string MakeImageSrcData(string filename)
{
byte[] filebytes = System.IO.File.ReadAllBytes(filename);
return "data:image/png;base64," +Convert.ToBase64String(filebytes, Base64FormattingOptions.None);
}
<img src="<%=MakeImageSrcData("c:\path\to\my.png") %>" />
https://devio.wordpress.com/2011/01/13/embedding-images-in-html-using-c/
http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/
Please check the below code, where I am able to generate the table dynamically from the database. But not able to display the link button inside the <td> element.
The basic function is to generate a new <tr> for every row in the database table with a link button added.
Aspx Code
<div style="width: 80%;" id="div_post" runat="server">
</div>
Aspx.cs Code
protected void GetvicharData()
{
try
{
Data_display dd = new Data_display();
DataTable dt = dd.disp_vichar();
string in_html = string.Empty;
int i = 0;
in_html = "<table style=\"width: 100%;\">";
foreach (DataRow dr in dt.Rows)
{
string str_build = string.Empty;
i = i + 1;
string lbDate = Convert.ToDateTime(dr["Date"]).ToString("dd-MMM-yy");
string lbTopic = dr["Topic_Name"].ToString();
string desc = dr["Description"].ToString();
string imgURL = dr["img_url"].ToString();
string textUrl = dr["txt_url"].ToString();
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
in_html += "</table>";
div_post.InnerHtml = in_html;
}
catch (Exception ex)
{
throw ex;
}
}
public string ret_string(string lbldate, string lbltopic, string description, string imgurl, string texturl, int i)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<tr><td class=\"post_date\" valign=\"top\" align=\"center\">");
sb.Append("<asp:Label ID=\"lblDate\" runat=\"server\">" + lbldate + "</asp:Label>");
sb.Append("</td><td class=\"post_topic\" valign=\"top\" >");
sb.Append(" <asp:Label ID=\"lblTopic" + i + "\" runat=\"server\">" + lbltopic + "</asp:Label>");
sb.Append("</td></tr><tr>");
sb.Append("<td class=\"ShowPic\" valign=\"top\" align=\"right\" ><img src=\"" + imgurl + "\" alt=\"\" id=\"img_post\" /></td>");
sb.Append("<td class=\"ShowPost\" valign=\"top\" style=\"text-align: justify\">");
sb.Append("<asp:Panel ID=\"pnlDesc" + i + "\" runat=\"server\"><p>" + description + "</p>");
sb.Append("</asp:Panel>");
sb.Append("<div><asp:LinkButton ID=\"lnkbtn" + i + "\" runat=\"server\" Text=\"Read more...\" onclick=\"lnkbtn1_Click\" OnClientClick=\"openNewWin('" + texturl + "')\" />");
sb.Append("</asp:LinkButton></div></td></tr>");
string sbuild = sb.ToString();
return sbuild;
}
catch (Exception ex)
{
throw ex;
}
}
As I am not able to figure it out that why my link button is showing hidden when I am rendering the page in the browser.
OK didn't test but,
sb.Append("</asp:LinkButton></div></td></tr>");
Where is the opening for the last </tr> ? . It seems to me its missing.
try sb.Append("</asp:LinkButton></div></td>"); instead
Also if it persist , try removing the last and putting it in a <tr><td> instead. One thing to put in mind also . Your ret_string method is in a a loop and therefore returns 1 row at a time. You can copy your ret_string method to an asp.net page and remove the C# codings, test and see if you have a successful row returned. Goodluck.
Update Also
OnClientClick=\"openNewWin('" + texturl + "')\" />");
Cn you try OnClientClick=\"openNewWin('" + texturl + "')\" >"); instead since i noticed you close the linkbutton in the next line already. So try remove the /> and see what happened?
Sorry Man. Just now when I see your code again It looks strange. I had to put another answer for i don't have any means of testing here. Like i mentioned in my previous answer, Your ret_string method is in a loop . Therefore your str_build should hold row ++ or one row at each loop instance. When you do like this..
foreach (DataRow dr in dt.Rows)
{
string str_build = string.Empty;
.................
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
First str_build; hold one row in the first going. However, when it comes another round, you set string str_build = string.Empty; , this automatically cleared whih cever row the str_build; is holding if i understand your code clear. I am not sure how you get your rows returned by , but i had suggest you take out the
string str_build = string.Empty;
and put it before your loop like below
string str_build = string.Empty;
foreach (DataRow dr in dt.Rows)
{
.................
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
Goodluck . try and see man....
I got my answer. Please check the code.
sb.Append("<a href=\"#\" onclick=\"openNewWin('" + texturl + "')\" >Read More...</a>");
I am trying to get some values from a List and then create a html table with this data but I can't get it to work properly.
I have:
HtmlTable table = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;
foreach(var item in Name)
{
row = new HtmlTableRow();
foreach(var familyName in item.familyName)
{
cell = new HtmlTableCell();
cell.InnerText = item.familyName.ToString();
row.Cells.Add(cell);
}
foreach (var givenName in item.givenName)
{
cell = new HtmlTableCell();
cell.InnerText = item.givenName.ToString();
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
this.Controls.Add(table);
When I step through the debugger I can see that row.Cells.Add(cell) contains the family name in the first loop and given name in the second loop but then something seems to be wrong and I can't get the table to show up on the page with this data.
When I check the table.rows.add(row) it says that
base {System.SystemException} = {"'HtmlTableRow' does not support the InnerText property."}
What am I doing wrong here?
I've stepped through your code and I can't replicate the error you mention.
It's difficult to say for sure without seeing your data structure Name but a couple of observations:
I. If familyName is a string, your inner foreach will execute once for each character in the string. This may not be what you want as it'll output a surname x number of times where x = surname.length.
This will result in unequal numbers of table cells per row unless all your surnames are the same length.
So I would say get rid of the
foreach(var familyName in item.familyName){...}
loop and just leave the code inside so it'll output surname just once.
II. I'm guessing that item.givenName is an array or collection e.g. List<> of strings? If so you could just use
cell.InnerText = givenName;
Note that this is will still give you uneven numbers of table cells per row because people have different numbers of forenames ;-)
Having said that you really ought to use the built in controls for doing this kind of thing - the Repeater is probably the way to go.
E.g.
Markup
<asp:Repeater runat="server" id="rptNames" onItemDataBound="rptName_ItemDataBound" >
<HeaderTemplate>
<table>
<tr>
<td>Given Name(s)</td>
<td>Family Name</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FamilyName") %></td>
<td>
<asp:Label runat="server" id="lGivenNames" />
</td>
</tr>
<ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
CodeBehind
Probably triggered by Page_Load - just bind your repeater to your Name collection:
rptNames.DataSource = Name;
rptNames.DataBind();
To output the GivenNames you use the ItemDataBound event which gets called for each row of the repeater:
protected void rptNames_ItemDataBound(object sender, RepeaterItemEventArgs e){
//Not interested the Header and Footer rows
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem){
Label l = ((Label)e.Item.FindControl("lGivenNames"));
string[] arrGivenNames = ((FullName)e.Item.DataItem).GivenNames;
foreach (string n in arrGivenNames){//could use a StringBuilder for a performance boost.
l.Text += n + " "; //Use a regular space if using it for Winforms
}
//For even slicker code, replace the Label in your repeater with another repeater and bind to that. Google `nested repeater` for a how to.
}
}
HTH.
Full Code
<h2>Doing it by hand - manually building up an HTML Table</h2>
<asp:Panel runat="server" ID="pnl1">
</asp:Panel>
<h2>With a Repeater</h2>
<asp:Repeater runat="server" id="rptNames" onItemDataBound="rptName_ItemDataBound" >
<HeaderTemplate>
<table border="1" style="border-color:Red;">
<tr>
<td>Given Name(s)</td>
<td>Family Name</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FamilyName") %></td>
<td>
<asp:Label runat="server" id="lGivenNames" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Testbed.WebControls
{
internal class FullName{
public string FamilyName{get;set;}
public string[] GivenNames{get;set;}
public FullName(){
}
public FullName(string[] _givenNames, string _familyName)
{
FamilyName = _familyName;
GivenNames = _givenNames;
}
}
public partial class HTMLTables : System.Web.UI.Page
{
List<FullName> Name;
protected void Page_Load(object sender, EventArgs e)
{
this.Name = new List<FullName>();
Name.Add(new FullName(new string[]{"Kylie"},"Minogue"));
Name.Add(new FullName(new string[]{"Angelina", "Kate", "Very-Lovely"}, "Jolie"));
Name.Add(new FullName(new string[]{"Audrey", "Veronica"},"Hepburn"));
HtmlTable table = new HtmlTable();
table.Border = 1;
HtmlTableRow row;
HtmlTableCell cell;
row = new HtmlTableRow();
cell = new HtmlTableCell();
cell.InnerText = "Given Name";
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = "Family Name";
row.Cells.Add(cell);
foreach (var item in Name)
{
row = new HtmlTableRow();
//foreach (var familyName in item.FamilyName){
cell = new HtmlTableCell();
cell.InnerText = item.FamilyName.ToString();
row.Cells.Add(cell);
//}
foreach (string givenName in item.GivenNames)
{
cell = new HtmlTableCell();
cell.InnerText = givenName.ToString();
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
this.pnl1.Controls.Add(table);
//Or do it with a repeater
rptNames.DataSource = Name;
rptNames.DataBind();
}
//This gets called everytime a data object gets bound to a repeater row
protected void rptName_ItemDataBound(object sender, RepeaterItemEventArgs e){
switch(e.Item.ItemType){
case ListItemType.Item:
case ListItemType.AlternatingItem:
string[] arrGivenNames = ((FullName)e.Item.DataItem).GivenNames;
foreach(string n in arrGivenNames){
((Label)e.Item.FindControl("lGivenNames")).Text += n + #" ";
}
break;
default:
break;
}
}
}
}