I have written this code to send an email when an change is made in a gridview.
I send an email with changes made in the column in row format. I need to add a line below each row and I am using this code and it doesn't work.
I have used this part to add line below rows sbMsg.AppendFormat("<table rules=" + rows + " style=' font-family:Calibri;background-color:#F1F1F1' width='1000'>");
public string mailFormatting(string Code)
{
List<string> lstSpecificColumns = new List<string>();
DataTable dtCurrentTbl = activeApplication.LoadMailActiveApplications(Code.ToString().Trim());
DataTable dtOldTbl = activeApplication.LoadMailLogManualUpdatesDetails(Code.ToString().Trim());
for (int colIndex = 0; colIndex < dtCurrentTbl.Columns.Count; colIndex++)
{
if (!dtCurrentTbl.Rows[0][colIndex].ToString().Equals(dtOldTbl.Rows[0][colIndex].ToString()))
{
lstSpecificColumns.Add(dtCurrentTbl.Columns[colIndex].ColumnName);
}
}
dtCurrentTbl.Merge(dtOldTbl);
DataTable resultTbl = dtCurrentTbl.AsEnumerable().CopyToDataTable().DefaultView.ToTable(true, lstSpecificColumns.ToArray());
string rows = "\"rows\"";
StringBuilder sbMsg = new StringBuilder();
sbMsg.AppendFormat("<p><font color=gray>Title<font></p>");
sbMsg.AppendFormat("<table rules= + rows + style='font-family:Calibri;background-color:#F1F1F1' width='1000'>");
sbMsg.AppendFormat("<tr> <td colspan='2'> <font color=blue> <u> " + Code.ToString().Trim() + " </u></font><td></tr>");
foreach (DataColumn dc in resultTbl.Columns)
{
sbMsg.AppendFormat("<tr>");
sbMsg.AppendFormat("<td> " + dc.ColumnName.Trim() + " </td>");
sbMsg.AppendFormat("<td> <strike>" + resultTbl.Rows[1][dc].ToString().Trim() + "</strike>" + " " + resultTbl.Rows[0][dc].ToString().Trim() + " </td>");
sbMsg.AppendFormat("</tr>");
}
sbMsg.AppendFormat("</table>");
return sbMsg.ToString();
}
Can anyone help me in this.
Related
I know there a some other questions related to mine but still they do not help me very much. I tried to understand the concept of the String.Format Method but i failed over and over again and still have no clue how to use it in my case. I know it is asked very much but if someone has an idea how to get the alignment in place i would appreciate it a lot.
I'm saving the output of different database tables to different text files. I want to align the "name" of the column to its "value". This makes very much sense because in some tables there a lot of "null" values and that leads to a poorly formatted output. Because the "null" is not exported to that file and therefore the values are moved to the left.
private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile)
{
string pathOfOutputFile = dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile;
using (SqlConnection sqlCon = new SqlConnection("Data Source=" +
GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
{
SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, sqlCon);
try
{
sqlCon.Open();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "nameOfDataset");
string currentLine = "";
foreach (var col in dataset.Tables[0].Columns)
{
currentLine += " " + col.ToString();
}
OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
foreach (DataRow row in dataset.Tables[0].Rows)
{
currentLine = "";
foreach (var item in row.ItemArray)
{
currentLine += " " + item.ToString();
}
OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
}
}
catch (Exception ex)
{
logger.Debug(ex, "Writing Database Output to the " + "\"" + nameOfOutputFile + "\"" + " file failed");
}
finally
{
sqlCon.Close();
}
}
}
string.Format is good when you know your required format in advance, less good if you have dynamic sources like the results of a query. Try something like this:
private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile)
{
string pathOfOutputFile = dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile;
using (SqlConnection sqlCon = new SqlConnection("Data Source=" +
GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
{
SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, sqlCon);
try
{
sqlCon.Open();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "nameOfDataset");
string currentLine = "";
var nameLengths = new int[dataset.Tables[0].Columns.Count];
var i = 0;
foreach (var col in dataset.Tables[0].Columns)
{
var colName = col.ToString();
nameLengths[i] = colName.Length;
currentLine += " " + colName;
i++;
}
OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
foreach (DataRow row in dataset.Tables[0].Rows)
{
currentLine = "";
i = 0;
foreach (var item in row.ItemArray)
{
var field = item.ToString();
currentLine += " " + field.PadRight(nameLengths[i], ' ');
i++;
}
OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
}
}
catch (Exception ex)
{
logger.Debug(ex, "Writing Database Output to the " + "\"" + nameOfOutputFile + "\"" + " file failed");
}
finally
{
sqlCon.Close();
}
}
}
If you get the length of the string representation of every column name and data value, you can work out the minimum width for each column and prepare a format string for that column which sets its minimum width.
Something like this:
using System;
using System.Data;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = SampleData();
// Prepare the column formats
int nCols = dt.Columns.Count;
var dataWidths = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName.Length).ToList();
foreach (DataRow d in dt.Rows)
{
for (int i = 0; i < nCols; i++)
{
dataWidths[i] = Math.Max(dataWidths[i], d.ItemArray[i].ToString().Length);
}
}
var colFormats = dataWidths.Select(x => $"{{0,{-x}}}").ToList();
//
var sb = new StringBuilder();
// Add the column names
sb.AppendLine(string.Join(" ", dt.Columns.Cast<DataColumn>().Select((x, i) => string.Format(colFormats[i], x.ColumnName))));
// Add in the data
foreach (DataRow d in dt.Rows)
{
sb.AppendLine(string.Join(" ", d.ItemArray.Select((x, i) => string.Format(colFormats[i], x))));
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
static DataTable SampleData()
{
DataTable sdt = new DataTable();
string[] cn = "ARCHIVE DBDATETIME NEXTDOCID HIGHESTDISK SYSTEMTYPE FLAGS VERSION SINGLEUSER".Split(' ');
foreach (string n in cn)
{
sdt.Columns.Add(n);
}
DataRow drn = sdt.NewRow();
drn["ARCHIVE"] = "Hello";
drn["DBDATETIME"] = 1316859;
drn["NEXTDOCID"] = 1;
drn["HIGHESTDISK"] = "Nothing";
drn["SYSTEMTYPE"] = 1;
drn["FLAGS"] = "ABC";
drn["VERSION"] = "Hello";
drn["SINGLEUSER"] = 256;
sdt.Rows.Add(drn);
drn = sdt.NewRow();
drn["ARCHIVE"] = "Value longer than header";
// No value for drn["DBDATETIME"] etc.
drn["SINGLEUSER"] = 256;
sdt.Rows.Add(drn);
return sdt;
}
}
}
Sample output:
ARCHIVE DBDATETIME NEXTDOCID HIGHESTDISK SYSTEMTYPE FLAGS VERSION SINGLEUSER
Hello 1316859 1 Nothing 1 ABC Hello 256
Value longer than header 256
I have used below code to show google chart, I want to show another graph when clicking on first graph and here need to pass the value ResourceId
if (resourceDetails != null)
{
dataTable.Columns.Add("ResourceName", typeof(string));
dataTable.Columns.Add("ResourceId", typeof(int));
dataTable.Columns.Add("Planned", typeof(float));
dataTable.Columns.Add("Actual", typeof(float));
foreach (var item in resourceDetails.Distinct().ToArray())
{
dt = GetIndividualData(item.ResourceId, projectId);
if (dt.Rows.Count > 0)
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
DataRow row = dataTable.NewRow();
row["ResourceName"] = item.ResourceName;
row["ResourceId"] = item.ResourceId;
row["Planned"] = float.Parse(dt.Rows[i]["Planned"].ToString());
row["Actual"] = float.Parse(dt.Rows[i]["Actual"].ToString());
dataTable.Rows.Add(row);
}
}
}
if (dataTable.Rows.Count > 0)
{
stringBuilder.Append(#"<script type=*text/javascript*> google.load( *visualization*, *1*, {packages:[*corechart*]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'ResourceName');
data.addColumn('number', 'ResourceId');
data.addColumn('number', 'Planned');
data.addColumn({type: 'string', role: 'style'});
data.addColumn('number', 'Actual');
data.addColumn({type: 'string', role: 'style'});
");
// data.addRows(" + dataTable.Rows.Count + ");
for (int i = 0; i <= dataTable.Rows.Count - 1; i++)
{
if (Convert.ToDecimal(dataTable.Rows[i]["Planned"]) > Convert.ToDecimal(dataTable.Rows[i]["Actual"]))
{
stringBuilder.Append("data.addRow(['" + dataTable.Rows[i]["ResourceName"].ToString() + "'," + dataTable.Rows[i]["ResourceId"].ToString() + ", " + dataTable.Rows[i]["Planned"].ToString() + ",\'color:DeepSkyBlue\'," + dataTable.Rows[i]["Actual"].ToString() + ",\'color:green\']);");
}
else
{
stringBuilder.Append("data.addRow(['" + dataTable.Rows[i]["ResourceName"].ToString() + "', " + dataTable.Rows[i]["ResourceId"].ToString() + "," + dataTable.Rows[i]["Planned"].ToString() + ",\'color:DeepSkyBlue\'," + dataTable.Rows[i]["Actual"].ToString() + ",\'color:red\']);");
}
}
stringBuilder.Append(" var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));");
stringBuilder.Append(" chart.draw(data, {width: 660, height: 500, title: 'Resource-Performance Graph',");
stringBuilder.Append("legend: {position: 'none'},");
stringBuilder.Append("hAxis: {title: 'Resource', titleTextStyle: {color: 'green'},slantedText:true},width:'645',colors: ['DeepSkyBlue','green'],");
stringBuilder.Append("vAxis:{title: 'Effort (Hr)',titleTextStyle: {color: 'green'}}");
stringBuilder.Append("});");
stringBuilder.Append(" google.visualization.events.addListener(chart, 'onmouseover', function() {$('#chart_div').css('cursor','pointer');});");
stringBuilder.Append(" google.visualization.events.addListener(chart, 'onmouseout', function() {$('#chart_div').css('cursor','default');});");
stringBuilder.Append("google.visualization.events.addListener(chart, 'select', function() {");
stringBuilder.Append("var selection = chart.getSelection();var row = selection[0].row;var col = selection[0].column;var rId = data.getValue(row, 1); var pid = '" + projectId + "'; var pname = '" + projectName + "'; var resId = '" + Convert.ToInt32((Session["ResourceId"])) + "';");
stringBuilder.Append("location.href = '" + ConfigurationManager.AppSettings["SiteLink"].ToString() + "/IndividualGraph.aspx?pId=' + pid + '&pName=' + pname +'&pResId=' + rId ; ");
stringBuilder.Append("});");
stringBuilder.Append("}");
stringBuilder.Append("</script>");
lt.Text = stringBuilder.ToString().Replace('*', '"');
}
}
here I have used ResouceId column to pass the value as a parameter, but it shows in chart as a column, how can I hide this column from showing?
You can use the DataView Class to hide columns
var data = new google.visualization.DataTable();
data.addColumn('string', 'ResourceName');
data.addColumn('number', 'ResourceId');
data.addColumn('number', 'Planned');
data.addColumn({type: 'string', role: 'style'});
data.addColumn('number', 'Actual');
data.addColumn({type: 'string', role: 'style'});
var view = new google.visualization.DataView(data);
view.hideColumns([1]); // array of column indexes to hide
However, it may make sense in this case to use a Row Property instead
which does not appear in the chart
You can define your own properties with
setRowProperty(rowIndex, name, value)
and
getRowProperty(rowIndex, name)
The DataTable Class also has methods for Column and Cell Properties
I am using tree view in my web application, but I am using dynamic input text box when tree view data bind. The code is:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
tables = node[0].ChildNodes[0].SelectNodes("col[#text='" + ds.Tables[0].Rows[i]["ModuleName"].ToString() + "']");
TreeNode MyRoot = new TreeNode();
string GUID = Guid.NewGuid().ToString();
MyRoot.Text = " " + ds.Tables[0].Rows[i]["ModuleName"].ToString() + " " + "<input type='text' id='" + GUID + "' />";
MyRoot.Value = ds.Tables[0].Rows[i]["ModuleName"].ToString();
if (RootNode != ds.Tables[0].Rows[i]["ModuleName"].ToString())
{
tv_GetMenu.Nodes.Add(MyRoot);
RootNode = ds.Tables[0].Rows[i]["ModuleName"].ToString();
var rows = from row in ds.Tables[0].AsEnumerable()
where row.Field<string>("ModuleName").Trim() == RootNode
select row;
DataTable dt = new DataTable();
dt = rows.CopyToDataTable();
if (dt != null)
{
if (dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
string GUID1 = Guid.NewGuid().ToString();
TreeNode MyChild = new TreeNode();
if ((dt.Rows[j]["PageName"].ToString().Trim() != "Master Config") && (dt.Rows[j]["PageName"].ToString().Trim() != "Upload") && (dt.Rows[j]["PageName"].ToString().Trim() != "label configuration") && (dt.Rows[j]["PageName"].ToString().Trim() != "Dashboard Report"))
{
MyChild.Text = " " + dt.Rows[j]["PageName"].ToString() + " " + "<input type='text' id='" + GUID1 + "' value='" + dt.Rows[j]["PageName"].ToString() + "'/>";
MyChild.Value = dt.Rows[j]["Address"].ToString();
MyRoot.ChildNodes.Add(MyChild);
}
}
}
}
}
}
The above code is working properly, but when I run the application and enter value in dynamic created text box then I am not getting this text box value for saving at run time. How we can access this value at run time?
Hi, I'm facing this problem getting the value of the checkbox value that I generated from C# code in a label. The output is just as I wanted, but i've tried using the below codes, but the object tells me its value is null. Someone please guide me, I need help.
HtmlInputCheckBox MyCheckBox = new HtmlInputCheckBox();
MyCheckBox = (HtmlInputCheckBox)this.FindControl("Qn" + temp);
bool isChacked = MyCheckBox.Checked;
MyMethod
string table1 = "";
ArrayList listofquestionnonradio = DBManager.GetSurveyQuestionNonRadio();
ArrayList listofallquestion = DBManager.GetAllSurveyQuestions();
int lastcount = Convert.ToInt32(listofquestionnonradio.Count);
table1 = "<br/><table>";
foreach (SurveyQuestions surv in listofallquestion)
{
if (surv.Questionid <= listofquestionnonradio.Count)
{
//get questions without radio
table1 += "<tr><td><b>Q" + temp + ")</b></td><td>" + surv.Question + "</td></tr><tr><td valign=top>Ans:</td><td>";
foreach (string subjname in listofselectsubjectnames)
{
//get name from excludelist
bool result= DBManager.GetExcludedQuestionsByQidAndSubject(surv.Questionid, subjname);
if (result == false)
{
string subvalue = subjname + "_val";
table1 += "<input type=checkbox name=Qn" + counterqn + " value=" + subvalue + " >" + subjname + "<br>";
counterqn++;
}
}
table1 += "<input type=checkbox name=lastqn value=NIL)>All of the above<br/></td></tr>";
table1 += "<tr style=height:10px></tr>";
temp++;
}
else
{
//get questions id if they are disable
bool result= DBManager.GetExcludedQuestionsByQid(surv.Questionid);
if (result == false)
{
//get questions with radio
table1 += "<tr><td><b>Q" + temp + ")<b></td><td>" + surv.Question + "</td></tr><tr><td valign=top>Ans:</td><td>";
table1 += "<input type=radio name=Qn" + counterqn + " value=1>Strongly disagree<br><input type=radio name=Qn" + counterqn + " value=2>Disagree<br><input type=radio name=Qn" + counterqn + " value=3>Agree<br><input type=radio name=Qn" + counterqn + " value=4>Strongly agree<br><input type=radio name=Qn" + counterqn + " value=5>Not applicable<br></td></tr>";
table1 += "<tr style=height:10px></tr>";
}
else
{
temp--;
}
temp++;
}
}
table1 += "</table><br/>";
I think the reason why you cannot access the checkbox controls is because you are not actually using server controls, you are building up your markup yourself. Your WebForm therefore does not have any controls to find.
If you are using ASP.NET WebForms (which is what I'm assuming) then why don't you use the server controls to build your table rather than manually building the HTML? You would then be able to view/modify them in your code-behind.
Take a look at the GridView control for a start to see how you could build up a table/grid-view easier than what you are currently doing.
In my application I am using a dataview for having the filters to be applied where the filter options are passed dynamically.if there are 2 filter parameters then the dataview should be filtered for parameter1 and then by parameter two. I am using a method which is called in a for loop where I am setting the count to the total no.of parameters selected using a listbox but the filtering is done only for the last parameter.
Here is my code:
string str = "";
for (int i = 0; i < listbox.Items.Count; i++)
{
if (listbox.Items[i].Selected)
{
if (str != string.Empty)
{
str = str + "," + listbox.Items[i].Text;
}
else
{
str = str + listbox.Items[i].Text;
}
}
}
string[] items = str.Split(',');
for (int i = 0; i < items.Length; i++)
{
ApplyFilter(items[i],dv);
}
private DataView ApplyFilter(string str,DataView newdv)
{
newdv.RowFilter = "[" + str + "]=" + ddl.SelectedItem.ToString();
return newdv;
}
Please provide a suitable solution .
Thanks in advance...
You should apply your filter altogether, not one by one :
newdv.RowFilter = "Column1 = " + value1 + " AND Column2 = " + value2;
So you can change your code as :
string[] items = str.Split(',');
string filter = string.Empty;
for (int i = 0; i < items.Length; i++)
{
filter += items[i] + " = " + dropdown.SelectedValue;
if (i != items.Length - 1)
{
filter += " AND ";
}
}
newdv.RowFilter = filter;
I think you should build a complete filter string and then set this filter to your DataView.
For example:
StringBuilder sb = new StringBuilder()
for (int i = 0; i < listbox.Items.Count; i++) {
if (!listbox.Items[i].Selected) {
continue;
}
if (sb.Length > 0) {
sb.Append(" and ");
}
sb.AppendFormat("[{0}] = {1}", listbox.Items[i].Text, ddl.SelectedItem);
}
dv.RowFilter = sb.ToString();
DataView dv = new DataView(dt);
string filterText = "some search criteria";
dv.RowFilter = "Column1 + Column2 + Column3 Like '%" + filterText + "%'";
I had a similar problem - but i think solution will be the same for both of them. I have a datatable that needs to be filtered by 5 controls and if they aren't filled - it shouldn't be filtered.
List<string> allParams = new List<string>();
//here add fields you want to filter and their impact on rowview in string form
if (tsPrzelewyTxtOpis.Text != ""){ allParams.Add("Opis like '%" + tsPrzelewyTxtOpis.Text + "%'"); }
if(tsPrzelewyTxtPlatnik.Text != ""){ allParams.Add("Płacący like '%" + tsPrzelewyTxtPlatnik.Text + "%'"); }
if(tsPrzelewyDropDownKonto.Text != "") { allParams.Add("Konto = '" + tsPrzelewyDropDownKonto.Text + "'"); }
if (tsPrzelewyDropDownWaluta.Text != "") { allParams.Add("Waluta = '" + tsPrzelewyDropDownWaluta.Text + "'"); }
if (tsPrzelewyDropDownStatus.Text != "") { allParams.Add("Status = '" + tsPrzelewyDropDownStatus.Text + "'"); }
string finalFilter = string.Join(" and ", allParams);
if (finalFilter != "")
{ (dgvPrzelewy.DataSource as DataTable).DefaultView.RowFilter = "(" + finalFilter + ")"; }
else
{ (dgvPrzelewy.DataSource as DataTable).DefaultView.RowFilter = ""; }