I have the following code, which adds rowspan to a datatable in an html string, but I want it not to receive as a parameter a datatable, but instead to receive as a parameter an html string in C#.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Subject");
dt.Columns.Add("Code");
dt.Columns.Add("Test");
dt.Columns.Add("Class");
dt.Rows.Add("Math", "9", "ABC", "D1");
dt.Rows.Add("Math", "9", "ABD", "D2");
dt.Rows.Add("Math", "9", "ABE", "D3");
dt.Rows.Add("Math", "9", "ABF", "D4");
dt.Rows.Add("Science", "91", "ABG", "D1");
dt.Rows.Add("Science", "91", "ABH", "D2");
dt.Rows.Add("Science", "91", "ABI", "D3");
dt.Rows.Add("English", "191", "ABJ", "D1");
Label1.Text = ConvertDataTableToHTML(dt);
}
public static string ConvertDataTableToHTML(DataTable dt)
{
string html = "<table border=1>";
//add header row
html += "<tr>";
for (int i = 0; i < dt.Columns.Count; i++)
{
html += "<td>" + dt.Columns[i].ColumnName + "</td>";
}
html += "</tr>";
//add rows
string sub = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
html += "<tr>";
int count = dt.Select("Subject ='" + dt.Rows[i][0].ToString() + "'").Count();
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < 2)
{
if (sub != dt.Rows[i][0].ToString())
{
html += "<td rowspan='" + count + "'>" + dt.Rows[i][j].ToString() + "</td>";
}
continue;
}
html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
}
sub = dt.Rows[i][0].ToString();
html += "</tr>";
}
html += "</table>";
return html;
}
This is the result that I hope
There are a few things wrong with the code, and a few ways you can improve your code:
<table border=1> is missing the quotes around the 1. It should be <table border='1'>.
You are missing the <thead> and <tbody> tags around the row tags.
Instead of constantly using +=, use a StringBuilder.
To make your code cleaner, you can change some of your for loops to foreach loops.
Your code should be changed to something like this:
public static string ConvertDataTableToHTML(DataTable dt)
{
StringBuilder builder = new StringBuilder();
//add header row
builder.Append("<table border='1'><thead><tr>");
foreach (DataColumn col in dt.Columns)
{
builder.Append("<td>");
builder.Append(col.ColumnName);
builder.Append("</td>");
}
builder.Append("</tr></thead><tbody>");
//add rows
string sub = "";
...
builder.Append("</tbody></table>");
return builder.ToString();
}
(Just apply the same concepts to the middle code that I removed.)
Related
i had a c# code where i was getting a table from sql database and mailing it as html table now i want to send two tables...how can i do that.
what i tried previously:
public static string HtmlTable(DataTable table)
{
try
{
string messageBody = "<font> " + "table value" + " </font><br><br>";
string empty_message = "Null DATA in table value";
if (table.Rows.Count == 0)
{
return empty_message;
}
string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
messageBody += htmlTableStart;
messageBody += htmlHeaderRowStart;
foreach (DataColumn column in table.Columns)
messageBody += htmlTdStart + column + htmlTdEnd;
messageBody += htmlHeaderRowEnd;
foreach (DataRow row in table.Rows)
{
messageBody += htmlTrStart;
foreach (var item in row.ItemArray)
{
messageBody += htmlTdStart;
messageBody += item;
messageBody += htmlTdEnd;
}
messageBody += htmlTrEnd;
}
messageBody += htmlTableEnd;
return messageBody;
}
catch (Exception ex)
{
return null;
}
}
the above code only generates one html table but what i need is i will be passing 2 tables. i need two tables to genertaed in my html. i will be passing two tables as arguments.on simple note i need 2 tables to be printed in my html body.
i will be passing two tables or data set which has two tables
public static string HtmlTable(DataTable table,datatable table2)
This could be as simple as including a builder method which will take in a list of DataTable using the seperation of concerns principle and build each table out, returning the end result for you to display to the client.
public static string HtmlTableBuilder(List<DataTable> tables)
{
string tableResponse = "";
foreach (var table in tables)
{
tableResponse += HtmlTable(table);
}
return tableResponse;
}
I have this string
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
that is composed of this c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('value1:\\n" +
string.Join(",", value1) + "');", true);
Using the code above the output is
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
Now I need to extract from this string from element number 5 to all subsequent elements, that is
2022-006,related,2022-007,related
and storing a row for each string value in a database table, that is
t
q
2022-006
related
2022-017
related
Expected output
2022-006
related
2022-017
related
But the expected ouput now is empty...
This is my c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
List<string> value2 = item.Split(',').ToList();
for (int i = 4; i < value2.Count; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
}
}
Thanks in advance for any help, really appreciated.
Solution
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
var requestDLL = string.Join(",", value1);
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
Output
2022-006
related
2022-017
related
Here you can find the code that return the expected output https://dotnetfiddle.net/8aBrZj
using System;
public class Program
{
public static void Main()
{
var requestDLL = "Dispatching System,proposal,to be sent,main,2022-006,related,2022-017,related";
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Console.Write(value2[i] + "\n" + value2[i + 1] + "\n \n");
i++;
}
}
}
This is my code to send datagridview as email. This code works for me by just sending the data in the datagridview.
Please guide me how to add the table header in it. I want the email to be sent as whole table including the table header.
var client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Credentials = new NetworkCredential("from_mail", "password");
var mail = new MailMessage();
mail.From = new MailAddress("from_mail");
mail.To.Add("to_mail");
mail.IsBodyHtml = true;
mail.Subject = "test";
string mailBody = "<table width='100%' style='border:Solid 1px Black;'>";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
mailBody += "<tr>";
foreach (DataGridViewCell cell in row.Cells)
{
mailBody += "<td>" + cell.Value + "</td>";
}
mailBody += "</tr>";
}
mailBody += "</table>";
//your rest of the original code
mail.Body = mailBody;
client.Send(mail);
MessageBox.Show("mail send");
this.Close();
For converting your DataGridView to HTML for sending it in an email, use the function below:
private StringBuilder DataGridtoHTML(DataGridView dg)
{
StringBuilder strB = new StringBuilder();
//create html & table
strB.AppendLine("<html><body><center><" +
"table border='1' cellpadding='0' cellspacing='0'>");
strB.AppendLine("<tr>");
//create table header
for (int i = 0; i < dg.Columns.Count; i++)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dg.Columns[i].HeaderText + "</td>");
}
//Close the header row
strB.AppendLine("</tr>");
//create table body
for (int i = 0; i < dg.Rows.Count; i++)
{
strB.AppendLine("<tr>");
foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
{
strB.AppendLine("<td align='center' valign='middle'>" +
dgvc.Value.ToString() + "</td>");
}
strB.AppendLine("</tr>");
}
//table footer & end of html file
strB.AppendLine("</table></center></body></html>");
return strB;
}
I am trying to get a button out to my asp page:
Div1.InnerHtml += "<td><input type=\"submit\" ID=\"Button3\" runat=\"server\" OnClick=\"Button3_Click\" value = \"start\" ></button></td> ";`
The error "Button3_Click " but the error "0x800a1391 - Microsoft JScript runtime error: 'Button3_Click' is undefined" keeps coming out. Button3_Click is also used in the same environment and works there.
Edited
More information on the workings of my code
Step 1 ) Receive a string, splits it and forms a 2D array. All of which is done in c#
Step 2 ) Output is then sent to the ASP page to be displayed in a table. The table would would have 5 columns with n number of rows. The first 3 cols are data from the string above and the next 2 rows are buttons that manipulate the data.
Listed below are some code snippets
public void createarray(string results)
{
using (StringReader reader = new StringReader(results))
{
int lineNo = -1;
string line;
int columncount = 3;
Div1.InnerHtml += "<table border = \"1\" style = \" font- size:13px ; width:20% \" ;> ";
while ((line = reader.ReadLine()) != null)
{
++lineNo;
twodarray(lineNo, columncount, line);
}// while
}// using
Div1.InnerHtml += "</table>";
}// end of function
public Array[] twodarray(int rowcount, int columncount, string parts)
{
string[,] twoD = new string[10000, 10];
string[] parts2 = parts.Split(new string[] { "," }, StringSplitOptions.None);
int y = rowcount;
for (int x = 0; x < columncount; x++)
{
twoD[y, x] = parts2[x];
}
Div1.InnerHtml += "<tr>";
Div1.InnerHtml += "<td>" + y + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 0].TrimStart('\\') + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 1] + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 2] + "</td>";
Div1.InnerHtml += "<td><input type = \"submit\" ID=\"Button4\" runat=\"server\" OnClick=\"retunthis\" Text=\"stop\">stop</submit></td> ";
Div1.InnerHtml += "</tr>";
return null;
}
The problem I am facing is that when the button is pressed there is no error message, there is no functions that are being processed.
At the moment I am just sending the data to the asp page through "innerhtml". is there a better way for be to display my output ?
Note: thanks to jack for editing my first question, and those who replies. <3
First you have an html tag mismatch. You are closing an input tag of type button with a button tag. This won't fix your error but promotes good syntax.
Karl's solution didn't work for me (I would have left a comment but I'm not a high enough reputation yet).
I tried a number of options, none of which do the trick. It appears that when ASP.NET renders HTML, it converts an asp:Button to an input type as you would expect but pulls out any submit events into scripts.
For example:
<asp:Button ID="Button3" Text="Start" runat="server" OnClick="Button3_Click" />
Renders to...
<input type="submit" name="ctl00$MainContent$Button3" value="Start" id="MainContent_Button3" />
Also rendered is...
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl01'];
if (!theForm) {
theForm = document.ctl01;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
I don't know where the event information is stored (maybe the view state) but it seems you would have to add this linkage as well.
Might just be easier to add the button in the HTML from the outright. If that's not possible, maybe try a ListView instead of a div and add buttons to the ListView.
I m developing a web project in asp.net 3.5
I want to export datatable to Excel. But there are 20.000 rows in datatable. Sometimes timeout problem happens..
protected string Worksheet97_Header()
{
string s = "<tr>";
foreach (ExcelColumn col in Columns)
{
s += "<th>" + col.Header_Text + "</th>";
}
s+="</tr>";
return s;
}
protected string Worksheet97_Data()
{
string s = "";
try
{
for (int i = 0; i < data.Rows.Count; i++)
{
s += "<tr>";
foreach (ExcelColumn col in Columns)
{
if (col.Column_Type == "System.String")
s += "<td>" + data.Rows[i][col.Field_Name].ToString() + "</td>";
if (col.Column_Type == "System.DateTime")
s += "<td>" + Convert.ToDateTime(data.Rows[i][col.Field_Name]).ToString("dd.MM.yyyy HH:mm:ss") + "</td>";
if (col.Column_Type == "System.Int32")
s += "<td>" + data.Rows[i][col.Field_Name].ToString() + "</td>";
if ((col.Column_Type == "System.Double") |
(col.Column_Type == "System.Decimal") |
(col.Column_Type == "System.Int16") |
(col.Column_Type == "System.Int32") |
(col.Column_Type == "System.Int64"))
s += "<td>" + Convert.ToDouble(data.Rows[i][col.Field_Name]).ToString("0.00") + "</td>";
}
}
}
catch (Exception ex)
{
string a = ex.ToString();
}
return s;
}
public string Export_Excel97()
{
string s = "";
s = "<table border=\"1\">";
s += Worksheet97_Header();
s += Worksheet97_Data();
s += "</table>";
return s;
}
Thanks.
IMHO, i think you should page the query so that you don't load everything into memory.
To write the excel file you may want to try this solution too and compare results of performance: http://msmvps.com/blogs/deborahk/archive/2009/07/23/writing-data-from-a-datatable-to-excel.aspx which will use Microsoft Excel Object Library, so you'll need to have Excel installed in the machine where you're running your code.
HTH somehow.
Regards!
This might help... http://www.dotnetjohn.com/PrintFriend.aspx?articleid=36
It is in VB.NET but you should be able to convert it anyway ;-)