how to hide a column from google visualization - c#

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

Related

Update Values in table with same id

I have 3 Tables
LaminationTitle**
LaminationTitleRelation
Papertypemaster
I Want to update Values of"LaminationTitleRelation" table which comes from CheckboxList... Below is my Update Form....
Lamination Title in Below form Updated in LaminationTitle Table, where as
Checkbox List Items should Update in LaminationTitleRelation Table
Note: if "Papertypeid" in LaminationTitleRelation and Items Checked are different then it should be add.
Plz help me
Use the following query:
query = "Create Table #PaperTypeMapping(LaminationTitleId int, PaperTypeId int)";
//For each value of Paper Type Id you will need to insert a row
query = "Insert Into #PaperTypeMapping(LaminationTitleId, PaperTypeId) Values(#laminationId, #paperTypeId)";
//Update existing values
query = "Update OldMapping Set OldMapping.ActiveStatus = 1 FROM LaminationTitleRelation OldMapping Inner join #PapertTypeMapping NewMapping ON OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId"
//Insert new values
query = "Insert into LaminationTitleRelation(lamTitleId, PapertTypeId, ActiveStatus) Select LaminationTitleId, PapertTYpeId, 1 From #PaperTypeMapping NewMapping where NOT EXISTS(SELECT 1 FROM LaminationTitleRelation OldMapping WHERE OldMapping.LamTitleId = NewMapping.LaminationTitleId and OldMapping.PaperTypeId = NewMapping.PaperTypeId)";
or alternatively you can use the following link a built in utility by MS SQL Merge
protected void btnUpdate_Click(object sender, EventArgs e) {
DB = new DBFunctions();
string vItems = mGetSelectedItems();
string vQuery = "Update laminationtitle Set title='" + txtLaminationTitle.Text + "',laminationtypeid='" + ddlProductType.SelectedValue + "' where laminationid='" + Request.QueryString["laminationid"] + "'";
int x = DB.SetData(vQuery);
DataTable dSelect = new DataTable();
DataTable dAll = new DataTable();
DB = new DBFunctions();
DB1 = new DBFunctions();
if (x > 0) {
int y = DB.SetData("delete from laminationtitlepapertyperelation where lamtitleid=" + Request.QueryString["laminationid"]);
if (y > 0) {
string[] values = vItems.Split(',');
for (int i = 0; i < values.Length; i++) {
vQuery = "insert into laminationtitlepapertyperelation(lamtitleid, papertypeid, activestatus)VALUES('" + Request.QueryString["laminationid"].ToString() + "','" + values[i] + "',1)";
DB.SetData(vQuery);
ScriptManager.RegisterStartupScript(this, GetType(), " Update Lamination Title", "alert('Lamination " + '"' + txtLaminationTitle.Text + '"' + " Title Updated Sucessfully');window.location='ManageLaminationTitle.aspx';", true);
}
}
}
}

How to retrieve value from dynamic text box using C#?

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?

C#.net MVC Passing parameter to load data from DB

I wanted to pass a value I got from my angular checkboxes .. ( number that has been checked) to query a certain data from my db.
Take a look on my connection query ..
private static string m_sConnectionString = ConfigurationManager.ConnectionStrings["NomsConnection"].ConnectionString;
private static string
m_sReport = "SELECT r.[RequestID],r.[RequestDate],r.[PARNumber],r.[StatusID],r.[PurchaseComment]" // 0 - 4
+ ",r.[UID],r.[LearUID],r.[FullName],r.[Email]" // 5 - 8
+ ",r.[EntityName],r.[DepartmentName],r.[DepartmentID]" // 9 - 11
+ ",r.[InboxLearUID]" // 12
+ ",r.[ProgramID],r.[ProgramCode],r.[ProgramName],r.[CostCenterCode]" // 13 - 16
+ ",p.[PartDesc],p.[SupplierID],p.[AccountType],p.[CurrName],p.[PartQuantity],p.[PiecePrice], p.[PartNumber]"
+ "FROM [NOP_PR].[dbo].[Requests] r "
+ "JOIN [NOP_PR].[dbo].[Parts] p on p.[RequestID] = r.[RequestID]"
+ "JOIN [NOP_PR].[dbo].[Departments] d on d.[DepartmentID] = r.[DepartmentID]"
+ "WHERE [CountryName] IN ('Philippines') ";
//ORDER BY r.[RequestDate] DESC";
public static List<NomsPRRequest> LoadPRfromDB_withParams(DateTime from, DateTime to, string EntityID,
string DepartmentID, string [] StatusID)
{
string sScript = m_sReport + ((EntityID == "") ? "" : " AND d.[EntityID]=" + EntityID) + ((DepartmentID == "") ? "" : " AND d.[DepartmentID]=" + DepartmentID)
+ " and [RequestDate] between '" + from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + to.ToString("yyyy-MM-dd HH:mm:ss") + "'" + " and " + (( __________ ) ? "" : " AND d.[StatusID] in (" + ____________ + ")" );
Dictionary<long, NomsPRRequest> data = new Dictionary<long, NomsPRRequest>();
long key;
double dAmount;
using (SqlConnection con = new SqlConnection(m_sConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(sScript, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
key = reader.GetInt64(0);
if (!data.ContainsKey(key))
{
data.Add(key, new NomsPRRequest()
{
RequestID = key,
RequestDate = reader.GetDateTime(1),
PARNumber = reader.GetString(2),
DepartmentName = reader.GetString(10),
DepartmentID = reader.GetInt64(11),
StatusID = reader.GetInt64(3),
FullName = reader.GetString(7),
InboxLearUID = reader.GetString(12),
ProgramName = reader.GetString(14),
ItemList = new List<NomsPRItem>(),
TotalAmount = 0.0
});
}
dAmount = (double)reader.GetDecimal(21) * (double)reader.GetDecimal(22);
data[key].TotalAmount += dAmount;
data[key].ItemList.Add(new NomsPRItem()
{
RequestID = key,
PartDesc = reader.GetString(17),
PartNumber = reader.GetString(23),
SupplierID = reader.GetString(18),
FullName = reader.GetString(7),
AccountType = reader.GetString(19),
CurrName = reader.GetString(20),
PartQuantity = (double)reader.GetDecimal(21),
PiecePrice = (double)reader.GetDecimal(22),
Amount = dAmount
});
}
}
}
return data.Values.ToList();
}
and that's it .. the query with underline is what I wanted to solve.
string sScript = m_sReport + ((EntityID == "") ? "" : " AND d.[EntityID]=" + EntityID) + ((DepartmentID == "") ? "" : " AND d.[DepartmentID]=" + DepartmentID)
+ " and [RequestDate] between '" + from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + to.ToString("yyyy-MM-dd HH:mm:ss") + "'" + " and " + (( __________ ) ? "" : " AND d.[StatusID] in (" + ____________ + ")" );
And also what to pass in my MVC Controller.
public JsonResult GetList()
{
DateTime today = DateTime.Now;
List<NomsPRRequest> model = NomsConnection.LoadPRfromDB_withParams(new DateTime(today.Year, today.Month, 1, 0, 0, 0), today,"","");
return Json(model, JsonRequestBehavior.AllowGet);
}
public JsonResult GetReportList(string from, string to, string EntityID="", string DepartmentID="", int StatusID)
{
DateTime fromd = DateTime.Now;
DateTime tod = DateTime.Now;
if (from != "undefined")
fromd = Convert.ToDateTime(from);
if (to != "undefined")
tod = Convert.ToDateTime(to);
fromd = new DateTime(fromd.Year, fromd.Month, fromd.Day, 0, 0, 0);
tod = new DateTime(tod.Year, tod.Month, tod.Day, 23, 59, 59);
return Json(NomsConnection.LoadPRfromDB_withParams(fromd, tod, EntityID, DepartmentID, StatusID), JsonRequestBehavior.AllowGet);
}
Here is my view
<ul class="dropdown-menu" role="menu" data-ng-click="$event.stopPropagation()">
<li data-ng-repeat="item in StatusList">
<label class="checkbox-inline">
<input type="checkbox" data-checklist-value="1" data-checklist-model="filter.StatusID" />
{{item}}
</label>
</li>
</ul>
and my angular
scope.array_ = angular.copy(scope.array);
scope.getStatus = http.get('GetStatusList').success(function (status) {
scope.StatusList = status;
});
PRApp.directive("checkboxGroup", function () {
return {
restrict: "A",
link: function (scope, elem, attrs) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function () {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function (a, b) {
return a - b
}));
});
}
}
});
Also what to add in this part when passing the data....
scope.changeDate = function () {
scope.models = null;
var e = document.getElementById("entityList");
scope.EntityID = e.options[e.selectedIndex].value;
e = document.getElementById("deptList");
scope.DepartmentID = e.options[e.selectedIndex].value;
// console.log(this.filter_fromDate);
//console.log(this.filter_toDate);
http.get('GetReportList?from=' + scope.filter_fromDate + '&to=' + scope.filter_toDate + '&EntityID=' + scope.EntityID + '&DepartmentID=' + scope.DepartmentID).success(
function (data) {
scope.models = data;
});
}
First of all your sql queries really should be parameterised to prevent SQL injection attacks.
Given that it seems that your problem is that you need your query to read .... AND d.statusid IN ( [status1], [status2], [status3] ......). To do this you can use parameters. First of all we need to set a parameter up for each string in StatusId
string sScript = m_sReport
+ ((EntityID == "") ? "" : " AND d.[EntityID]="
+ EntityID) + ((DepartmentID == "") ? "" : " AND d.[DepartmentID]="
+ DepartmentID) + " and [RequestDate] between '"
+ from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '"
+ to.ToString("yyyy-MM-dd HH:mm:ss") + "'" + " and "
+ (( __________ ) ? "" : " AND d.[StatusID] in (";
int paramCount=0;
foreach(string Id in StatusId)
{
sScript = sScript + "#statusParam" + paramCount + ",";
paramCount++;
}
sScript = sScript + ");";
next we need to fill the each parameter, so after we've initialised the connection etc:
using (SqlCommand command = new SqlCommand(sScript, con))
{
paramCount = 0;
foreach(string Id in StatusId)
{
string paramName = "#statusParam" + paramCount;
command.Parameters.AddWithValue(paramName,Id);
paramCount++;
}
SqlDataReader reader = command.ExecuteReader();
/*..........rest of the code */
}
I've not stuck this in any IDE so there may be minor syntax errors, but you get the idea.

Add lines below rows dynamically

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.

Filtering DataView with multiple columns

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 = ""; }

Categories