Merge two objects in Coldfusion(using openBD) issue - object

I have the following code block:
<cfset docs1 = StructNew() />
<cfset docs1['content'] = "I am" />
<cfset docs1['ida'] = "23" />
<cfset docs1['solrid'] = "23_solrid" />
<cfset docs1['title'] = "Aaaaa" />
<cfset docs2 = StructNew() />
<cfset docs2['content'] = "the most" />
<cfset docs2['ida'] = "1" />
<cfset docs2['solrid'] = "1_solrid" />
<cfset docs2['title'] = "Bbbb" />
<cfset docs3 = StructNew() />
<cfset docs3['content'] = "crap coder" />
<cfset docs3['ida'] = "7" />
<cfset docs3['solrid'] = "7_solrid" />
<cfset docs3['title'] = "Cccc" />
<cfset docs4 = StructNew() />
<cfset docs4['content'] = "in the whole universe!" />
<cfset docs4['ida'] = "39" />
<cfset docs4['solrid'] = "39_solrid" />
<cfset docs4['title'] = "Dddd" />
<cfscript>
doca = ArrayNew();
ArrayAppend(doca, docs1);
ArrayAppend(doca, docs2);
ArrayAppend(doca, docs3);
ArrayAppend(doca, docs4);
</cfscript>
<cfset forsolr1 = StructNew()>
<cfset forsolr1['docs'] = doca>
<cfset forext1 = SerializeJson(forsolr1)>
<cfdump var="#forsolr1#" label="Struct1">
<cfoutput>
#forext1#
</cfoutput>
<br /><br /><br />
<cfset docsh = StructNew() />
<cfset docsh['23_solrid'] = "I need" />
<cfset docsh['1_solrid'] = "to read" />
<cfset docsh['7_solrid'] = "a lot of" />
<cfset docsh['39_solrid'] = "programming books!" />
<cfset i = 1>
<cfset solrid = "solrid">
<cfset result = ArrayNew(1)>
<cfloop collection="#docsh#" item="key" >
<cfset innerstruct = StructNew()>
<cfset innerstruct['solrid'] = #key#>
<cfset innerstruct['dochighlighted'] = #docsh[key]#>
<cfset result[i] = innerstruct>
<cfset i = i + 1>
</cfloop>
<cfset forsolr = StructNew()>
<cfset forsolr['docs'] = result>
<cfset forext = SerializeJson(forsolr)>
<cfdump var="#forsolr#" label="Struct2">
<cfoutput>
#forext#
</cfoutput>
The result are two objects(struct of array of structs):
First object
{
"docs":[
{
"content":"I am",
"ida":"23",
"solrid":"23_solrid",
"title":"Aaaaa"
},
{
"content":"the most",
"ida":"1",
"solrid":"1_solrid",
"title":"Bbbb"
},
{
"content":"crap coder",
"ida":"7",
"solrid":"7_solrid",
"title":"Cccc"
},
{
"content":"in the whole universe!",
"ida":"39",
"solrid":"39_solrid",
"title":"Dddd"
}
]
}
Second object
{
"docs":[
{
"solrid":"23_solrid",
"dochighlighted":"I need"
},
{
"solrid":"1_solrid",
"dochighlighted":"to read"
},
{
"solrid":"7_solrid",
"dochighlighted":"a lot of"
},
{
"solrid":"39_solrid",
"dochighlighted":"programming books!"
}
]
}
Is it possible to merge these two objects into one in the form of(copy second to the first):
{
"docs":[
{
"content":"I am",
"ida":"23",
"solrid":"23_solrid",
"title":"Aaaaa",
"dochighlighted":"I need"
},
{
"content":"the most",
"ida":"1",
"solrid":"1_solrid",
"title":"Bbbb",
"dochighlighted":"to read"
},
{
"content":"crap coder",
"ida":"7",
"solrid":"7_solrid",
"title":"Cccc",
"dochighlighted":"a lot of"
},
{
"content":"in the whole universe!",
"ida":"39",
"solrid":"39_solrid",
"title":"Dddd",
"dochighlighted":"programming books!"
}
]
}
I had tried structAppend function with no result. This function cannot append deep nested elements. Is it possible to retain order? The reason for that is that the above objects are search engine's results, so it is very important to keep the original order. Is it possible to merge two objects by key reference? The reason that I am asking is that the first object is coming out from the search engine in a specific order (notice the solrid) but the second object may not. Example:
*First object*
{
"docs":[
{
"content":"I am",
"ida":"23",
"solrid":"23_solrid",
"title":"Aaaaa"
},
{
"content":"the most",
"ida":"1",
"solrid":"1_solrid",
"title":"Bbbb"
},
{
"content":"crap coder",
"ida":"7",
"solrid":"7_solrid",
"title":"Cccc"
},
{
"content":"in the whole universe!",
"ida":"39",
"solrid":"39_solrid",
"title":"Dddd"
}
]
}
*Second object*
{
"docs":[
{
"solrid":"39_solrid",
"dochighlighted":"programming books!"
},
{
"solrid":"7_solrid",
"dochighlighted":"a lot of"
},
{
"solrid":"1_solrid",
"dochighlighted":"to read"
},
{
"solrid":"23_solrid",
"dochighlighted":"I need"
}
]
}
Is it possible to achieve the same -as above- merging result?
{
"docs":[
{
"content":"I am",
"ida":"23",
"solrid":"23_solrid",
"title":"Aaaaa",
"dochighlighted":"I need"
},
{
"content":"the most",
"ida":"1",
"solrid":"1_solrid",
"title":"Bbbb",
"dochighlighted":"to read"
},
{
"content":"crap coder",
"ida":"7",
"solrid":"7_solrid",
"title":"Cccc",
"dochighlighted":"a lot of"
},
{
"content":"in the whole universe!",
"ida":"39",
"solrid":"39_solrid",
"title":"Dddd",
"dochighlighted":"programming books!"
}
]
}
Many many thanks,
With honour,
Tom
Greece

This should get you pretty far:
<cffunction name="ArrayOfStructsMerge" returntype="array" access="public" output="yes">
<cfargument name="left" type="array" required="yes">
<cfargument name="right" type="array" required="yes">
<cfargument name="id" type="string" required="yes">
<cfset var result = Duplicate(arguments.left)>
<cfset var element = "">
<cfset var key = "">
<cfset var currentId = "">
<cfset var lookup = StructNew()>
<cfloop array="#result#" index="element">
<cfif IsStruct(element) and StructKeyExists(element, arguments.id)>
<cfset currentId = element[arguments.id]>
<cfset lookup[currentId] = element>
</cfif>
</cfloop>
<cfloop array="#arguments.right#" index="element">
<cfif IsStruct(element) and StructKeyExists(element, arguments.id)>
<cfset currentId = element[arguments.id]>
<cfif StructKeyExists(lookup, currentId)>
<cfloop collection="#element#" item="key">
<cfset lookup[currentId][key] = Duplicate(element[key])>
</cfloop>
<cfelse>
<cfset ArrayAppend(result, Duplicate(element))>
</cfif>
</cfif>
</cfloop>
<cfreturn result>
</cffunction>
It operates non-destructively (without modifying the original objects). Call it like this:
<cfset result = ArrayOfStructsMerge(obj1.docs, obj2.docs, "solrid")>
<cfdump var="#result#">
<cfset a1 = [{id: 1, a: "a1"}, {id: 2, a: "a2"}, {id: 4, d: "d4"}]>
<cfset a2 = [{id: 1, a: "a1-new"}, {id: 2, b: "b2"}, {id: 3, c: "c3"}]>
<cfset a3 = ArrayOfStructsMerge(a1, a2, "id")>

Related

PF6 SelectOneMenu filter is not fired with "Paste" or with "CTRL + Backspace"

Using PrimeFaces 6, I am trying to filter my p:selectOneMenu when the user paste a value or when the user delete a value using CTRL + Backspace, in another word, when the value got changed anyhow.
Please find my below code.
<p:selectOneMenu id="providerURLDD" widgetVar="providerURLDD"
value="#{switchProviderBean.selectedProvider}"
panelStyle="width:240px" effect="fade" filter="true"
style="width:240px" filterMatchMode="contains"
required="true"
requiredMessage="#{msg['selectProvider']}">
<f:selectItem itemLabel="Select" />
<f:selectItems value="#{switchProviderBean.providerAccounts}"
var="providerAcc"
itemLabel="#{providerAcc.code}-#{providerAcc.switchAccountId}-#{providerAcc.name}"
itemValue="#{providerAcc.switchAccountId}" />
</p:selectOneMenu>
I also tried to use Javascript like this:
function getTextAreaSelection(textarea) {
var start = textarea.selectionStart,
end = textarea.selectionEnd;
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end)
});
}, 1);
};
}
var textarea = document.getElementById("switchProviderChoice:providerURLDD_filter");
detectPaste(textarea, function(pasteInfo) {
console.log('perform filter');
PF('providerURLDD').filter();
});

Update cell update without scroll to top

I have an issue where on updating a cell with cellEdited, The page jumps back to the top of the page when the mutator or formatter is called.
I've tried setting table.redraw(false) and then the formatter/mutator doesn't seem to do anything.
When a user updates the proficiency level the formatter or mutator should add a button if it's above 3. It works perfectly. However it jumps to the top of the screen.
Any help appreciated.
var evidenceMutator = function(value, data, type, params, component){
skillsTable.redraw(false);
var claimedProficiency = data.Proficiency;
var skillClaimed = data.SkillID;
var Evidence = data.Evidence;
var memberID = $("#user").data("memberid");
if (claimedProficiency >= 3 ) {
// has provided evidence
if (Evidence == 1) {
return '<a class="btn btn-outline-success btn-xs btn-slim evidence" href="#" id="'+ skillClaimed + '" onclick="openEvidenceModal(this, this.id, '+ memberID +')"> <i class="fas fa-check-circle cssover"></i> Edit Evidence </a>';
} else { // needs to provide
return '<a class="btn btn-outline-danger btn-xs btn-slim evidence" href="#" id="'+ skillClaimed + '" onclick="openEvidenceModal(this, this.id, '+ memberID +')"> <i class="fas fa-times-circle cssover"></i> Add Evidence </a>';
}
} else {
// cell.getElement().style.color = "#CCD1D1";
//cell.getElement().style.fontStyle ="italic";
// cell.getElement().style.fontSize = "0.75em";
return ' No Evidence Needed';
}
}
function complianceTick(cell) {
var isCompliant = cell.getData().Compliance;
var Evidence = cell.getData().Evidence;
var claimedProficiency = cell.getData().Proficiency;
// style all with sucesss and only change if we need to
cell.getElement().style.color = "#33CC66";
cell.getElement().style.fontSize = "0.85em";
cell.getElement().style.fontStyle = "italic";
if (claimedProficiency >= 3 ) {
if (Evidence == '1') {
return '<i class="fas fa-check-circle"></i>';
} else {
cell.getElement().style.color = "#FF0000";
cell.getElement().style.fontSize = "0.85em";
cell.getElement().style.fontWeight = "bold";
return '<i class="fas fa-times-circle"></i>';
}
} else {
return '';
}
}
var skillsTable = new Tabulator("#SkillsTable", {
index: "SkillID",
height:"100%",
headerVisible:false,
autoResize:true,
layout:"fitColumns", //fit columns to width of table
groupBy:"SkillCatID",
groupHeader: groupMaker,
initialSort:[ //set the initial sort order of the data
{column:"RowOrder", dir:"asc"}
],
columns:[ //define the table columns
{title:"", field:"SkillID", visible:false},
{title:"Skill", field:"SkillName", visible:true, headerSort:false, formatter: skillName},
{title:"", field:"SkillCatID", visible:false},
{title:"", field:"SkillCatName", visible:false},
{title:"My Level", field:"Proficiency", visible:true, editor:inputEditor, formatter:prof, width:"7%", headerSort:false, align:"center",
cellEdited:function(cell, row, success){ // EDITING FUNCTION
var $value = cell.getValue();
var $field = cell.getField();
var $row = cell.getRow();
var $id = $row.getData().SkillID;
var integer = parseInt($value, 10);
if ($value != "" && integer < 5 && integer >= 0) {
// update record
updateRecord($id, $field, $value, $row);
//$row.update({"Proficiency" : $value});
//$row.update({"Evidencer" : $value});
skillsTable.updateRow($id, {id:$id,"Proficiency":$value});
skillsTable.updateRow($id, {id:$id,"Evidencer":$value});
} else {
cell.restoreOldValue();
if ($value != "") {
alert ("Values should be between 0 and 4, the cell has been restored to its previous value.")
}
}
},
},
{title:"Target", field:"MinLevel", visible:false, headerSort:false},
{title:"", field:"Proficiency", visible:true, formatter: skillDec, headerSort:false},
{title:"Evidence", field:"Evidencer", visible:true, hozAlign:"center", formatter: evidenceCell, mutator: evidenceMutator, width:"10.5%", headerSort:false},
{title:"", field:"RowOrder", visible:false, sorter:"number"},
{title:"disc", field:"DisciplineID", visible:false, headerFilter:true}
],
});
UPDATE
I think I've narrowed down the issue to the formatter:
```
function evidenceCell(cell, formatterParms, onRendered) {
var claimedProficiency = cell.getData().Proficiency;
var skillClaimed = cell.getData().SkillID;
var Evidence = cell.getData().Evidence;
var memberID = $("#user").data("memberid");
if (claimedProficiency >= 3 ) {
// has provided evidence
if (Evidence == 1) {
return '<a class="btn btn-outline-success btn-xs btn-slim evidence" href="#" id="'+ skillClaimed + '" onclick="openEvidenceModal(this, this.id, '+ memberID +')"> <i class="fas fa-check-circle cssover"></i> Edit Evidence </a>';
} else { // needs to provide
return '<a class="btn btn-outline-danger btn-xs btn-slim evidence" href="#" id="'+ skillClaimed + '" onclick="openEvidenceModal(this, this.id, '+ memberID +')"> <i class="fas fa-times-circle cssover"></i> Add Evidence </a>';
}
} else {
cell.getElement().style.color = "#CCD1D1";
cell.getElement().style.fontStyle ="italic";
cell.getElement().style.fontSize = "0.75em";
return 'No Evidence Needed';
}
}
```
It looks like the issue is with the cell.getData(). It seems to trigger the scroll to the top of page. I think it may be a bug with the newer version. Testing 4.2 and it seems to not be an issue. However, I have issues with modals going to the top of the page with the older version.
The issue seems to be with the virtual DOM. In my case I can luckily turn it off by using the following:
virtualDom:false,
I'm not sure this would be a good fix for people with hundreds of rows.

can't get Object when it is Selected

File: ServiceAnnonce.java
public List<Annonce> loadAnnonce( UserEntity idUser ) {
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.annonceUser= :idUser" ).setParameter( "idUser", idUser );
List<Annonce> annonce = (List) query.getResultList();
return annonce;
}
File : DaoUser.java
public UserEntity loadUserByEmail( String email ) {
Assert.notNull( email );
UserEntity user = null;
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.email= :email" ).setParameter( "email", email );
try {
user = (UserEntity) query.getSingleResult();
} catch ( NoResultException e ) {
}
return user;
}
File : ServiceUser.java
public Annonce annonceEnFonctionId( Annonce annonce, String email ) {
UserEntity user = userDao.loadUserByEmail( email );
List<Annonce> a = annonceDao.loadAnnonce( user );
Annonce an = annonce;
for ( int i = 0; i < a.size(); i++ ) {
if ( a.get( i ).getId() == (Long) an.getId() ) {
an = annonce;
}
}
return an;
}
File: flow.xml
<transition on="annonceID" to="annonceEnFonctionId">
<evaluate expression="userService.annonceEnFonctionId(annonce,user.getEmail())" result="flowScope.annonce" />
</transition>
File : OurAnnonce.java
<p:dataTable var="item" value="#{annonce}">
<p:column style="width:2%">
<h:commandButton value="show" action="annonceID" />
</p:column>
<p:column>
<h:outputText value="#{item.titre}" />
</p:column>
File:shwo.java
<p:dataTable var="valeur" value="#{annonce}">
<p:column headerText="Model">
<h:outputText value="#{valeur.titre}" />
</p:column>
</p:dataTable>
when i click Button show i should get more detail of annonce selected but i still get always the first annonce in DataBase any idea ??

Range Slider for text values

I need a range slider just like below site has the options cut, Clarity and color has slider
http://www.lumeradiamonds.com/diamonds/search?shapes=B,PR,O,M,P,C,E,AS,R,H&
how to add range slider for color or text values like good better best
If anybody tell me how can i implement same slider in my site than its very helpful to me
Thanks
Try this out:
function updateTextInput() {
var value1 = Number(document.getElementById("range").value);
var value2 = "";
if ( value1 === 0 ) {
value2 = "Blue Diamonds";
// Insert more code here for what you intend to do
}
else if ( value1 === 1 ) {
value2 = "Blue Diamonds";
// Insert more code here for what you intend to do
}
else if ( value1 === 2 ) {
value2 = "Red Diamonds";
// Insert more code here for what you intend to do
}
else if ( value1 === 3 ) {
value2 = "Black Diamonds";
// Insert more code here for what you intend to do
}
else if ( value1 === 4 ) {
value2 = "Green Diamonds";
// Insert more code here for what you intend to do
}
document.getElementById('value2').innerHTML = value2;
}
<form>
<input id="range" type="range" name="rangeInput" min="0" step="1" max="4" value="2" class="white" onchange="updateTextInput(this.value);" onchange="updateTextInput(this.value);" oninput="amount.value=rangeInput.value">
<input oninput="rangeInput.value=amount.value" id="box" type="text" value="0" name="amount" for="rangeInput" onkeyup="updateTextInput(this.value);" oninput="amount.value=rangeInput.value" />
</form>
<p id="value2">Red Diamonds</p>

asp gridview export to excel hide column

Can someone please take a look at my code? this code works perfectly but i want to remove the 1st and 2nd column when the data exported to excel. i try GridView1.Columns[0].Visible = false; but its not working.
here's my aspx
<%# Page Title="VRQ" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="EmployeePage.aspx.cs" Inherits="EmployeePage"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('innerdata').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
function OpenFile(KEYW) {
window.open("ResumePage.aspx?bid=" + KEYW, "ResumeContext");
}
</script>
<asp:Button ID="btnbacksearch" runat="server" Text="Back to Search"
Width="127px" OnClick="btnbacksearch_Click" CssClass="plainbutton" />
<asp:Button ID="btnExportToExcel" runat="server" OnClick="btnExportToExcel_Click"
Text="Export Results to Excel" Width="174px" CssClass ="plainbutton" />
<asp:Button
ID="btnGenerateSF" runat="server" OnClick="btnGenerateSF_Click"
Text="Generate Resume" Width="137px" CssClass ="plainbutton"
Visible="False" />
<asp:DropDownList ID="ddStatus" runat="server"
onselectedindexchanged="ddStatus_SelectedIndexChanged" AutoPostBack="True"
Visible="False" Width="150px">
<asp:ListItem Selected="True" Value="Active">Active Personnel</asp:ListItem>
<asp:ListItem Value="Inactive">Inactive Personnel</asp:ListItem>
</asp:DropDownList>
<div style="font-size: 11pt; font-family: Tahoma; text-align:center "><strong>
SEARCH SUMMARY</strong></div>
<div style="font-size: 10pt; font-family: Tahoma; text-align:center ">
<asp:Label ID="LabelCaption" runat="server" Text="Label"></asp:Label>
</div>
<div id = "innerdata" style="size: landscape;" >
<asp:GridView ID="GridView1" runat="server"
CellPadding="4" DataSourceID="SqlDataSource1"
onrowcreated="GridView1_RowCreated"
AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
DataKeyNames="IDNo" AllowSorting="True" Width="100%"
PageSize="30" EmptyDataText="No Existing Records." CssClass="GridView"
onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False"
onsorted="GridView1_Sorted" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkSelect" Text="View" CommandName ="Select" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkPrintRep1" Text="Project Selection" CommandName ="PrintSF330" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="70px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="fullname" HeaderText="Name" ReadOnly="True"
SortExpression="fullname" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="YearsExperience" HeaderText="Experience"
SortExpression="YearsExperience" >
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Job" HeaderText="Position" SortExpression="Job" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Search Results" SortExpression ="SearchDetails">
<ItemTemplate>
<%# HighlightText(Convert.ToString(Eval("SearchDetails"))) %> </ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
<RowStyle CssClass="GridRowStyle"/>
<PagerStyle HorizontalAlign="Center" />
<SelectedRowStyle CssClass="GridSelected" />
<HeaderStyle CssClass="GridHeader" Height="10px" />
<PagerStyle CssClass="GridFooterStyle"/>
</asp:GridView></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HRIS_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:HRIS_ConnectionString.ProviderName %>"
SelectCommand="select i.IDNo,concat(lastname,', ',firstname,' ',middlename) as fullname,e.tYrsExperience as YearsExperience,p.Description as Job,'' as SearchDetails FROM employeesinfo i inner join ecd e on e.empid=i.idno
left outer join Position p on p.idno = e.presentjob">
</asp:SqlDataSource>
<vt:MessageBox ID="MessageBox1" runat="server"></vt:MessageBox>
</asp:Content>
and here's my aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
public partial class EmployeePage : System.Web.UI.Page
{
string sqry = ""; string scolumn = "";
string origQry = String.Empty;
public string keyword = "";
public string curAlpha = "";
public int iCtr = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["QRY_CONDITIONS"] == null) Response.Redirect("Default.aspx");
scolumn = Session["QRY_DETAIL"].ToString();
sqry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user == null) return;
if (user.IsSuperAdmin && sqry == "ALL")
{
ddStatus.Visible = true;
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") ;
}
else if(sqry == "ALL")
{
ddStatus.Visible = false;
sqry = " where ifnull(i.activestatus,0) = 1 ";
}
origQry = sqry;
if (Request.QueryString["keyword"] != null) keyword = Request.QueryString["keyword"].ToString().TrimEnd().TrimStart();
if (!IsPostBack)
{
if (keyword == "")
{
sqry = sqry + " and i.lastname like 'A%' ";
Session["QRY_alpha"] = " and i.lastname like 'A%' ";
curAlpha = "A";
}
LoadStates();
BindData();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
curAlpha = (string)ViewState["curAlpha"];
}
protected override object SaveViewState()
{
ViewState["curAlpha"] = curAlpha;
return base.SaveViewState();
}
private void BindData()
{
modPublic myMod = new modPublic();
SqlDataSource1.SelectCommand = "SELECT distinct i.idno,concat(i.lastname,', ',i.firstname,' ',i.middlename) as fullname,e.tYrsExperience as YearsExperience,e.Position as Job," + scolumn + " as SearchDetails FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + sqry + " order by i.lastname,i.firstname";
SqlDataSource1.Select(new DataSourceSelectArguments());
object o = myMod.ExecuteScalar("select count(distinct i.idno) as ctr FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + origQry + " ");
LabelCaption.Text = o.ToString() + " Record(s) found";
if (keyword == "")
{
GridView1.AllowPaging = false;
GridView1.Columns[5].Visible = false;
}
else
{
GridView1.Columns[5].Visible = true;
}
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AlphaPaging")
{
curAlpha = e.CommandArgument.ToString();
sqry = sqry + " and i.lastname like '" + e.CommandArgument + "%'";
Session["QRY_alpha"] = " and i.lastname like '" + e.CommandArgument + "%'";
GridView1.AllowPaging = false;
BindData();
SaveStates();
//this.SqlDataSource1.SelectCommand = "Select * from [Table_1] WHERE theName LIKE '" + e.CommandArgument + "%'";
}
if (e.CommandName == "PrintSF330")
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=" + e.CommandArgument.ToString() + " ");
}
else if (e.CommandName == "Select")
{
SaveStates();
loadECD(e.CommandArgument.ToString());
}
}
//protected override object SaveViewState()
//{
// ViewState["alphacond"] = alphacond;
// return base.SaveViewState();
//}
//protected override void LoadViewState(object savedState)
//{
// if (Page.IsPostBack)
// {
// base.LoadViewState(savedState);
// alphacond = ViewState["alphacond"].ToString();
// }
//}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// e.Row.Attributes.Add("OnClick", "javascript:" + Page.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
if (keyword == "")
{
if (e.Row.RowType == DataControlRowType.Footer)
{
GridViewRow grv = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
this.GridView1.Controls[0].Controls.Add(grv);
TableCell cell = new TableCell();
grv.Cells.Add(cell);
if (keyword == "")
cell.ColumnSpan = 5;
else
cell.ColumnSpan = 6;
for (int i = 65; i <= (65 + 25); i++)
{
string s = Char.ConvertFromUtf32(i);
if (s == curAlpha)
{
Label lt = new Label();
lt.Text = "[" + s + "]";
lt.Font.Bold = true;
lt.Font.Size = new FontUnit(12);
lt.Style["text-align"] = "middle";
cell.Controls.Add(lt);
}
else
{
LinkButton lb = new LinkButton();
lb.Text = s + " ";
lb.CommandArgument = s;
lb.CommandName = "AlphaPaging";
cell.Controls.Add(lb);
}
}
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
GridView1.Columns[0].Visible = false;
GridView1.AllowPaging = false;
BindData();
GridView1.DataBind();
GridViewExportUtil.Export("ReportResultsPage.xls", this.GridView1);
GridView1.AllowPaging = true;
BindData();
GridView1.Columns[0].Visible = false;
}
private void SaveStates()
{
if (Session["QRY_alpha"] == null) Session["QRY_alpha"] = "";
sqry = Session["QRY_CONDITIONS"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user.IsSuperAdmin && sqry == "ALL")
{
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") + Session["QRY_alpha"].ToString();
origQry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0");
}
else if (sqry == "ALL")
{
sqry = " where ifnull(i.activestatus,0) = 1 " + Session["QRY_alpha"].ToString();
origQry = " where ifnull(i.activestatus,0) = 1 ";
}
else
{
sqry = Session["QRY_CONDITIONS"].ToString() + Session["QRY_alpha"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
}
string tmp = "";
tmp = sqry + "|" +
scolumn + "|" +
keyword + "|" +
GridView1.SelectedIndex.ToString() + "|" +
GridView1.PageIndex.ToString() + "|" +
ddStatus.SelectedIndex.ToString() + "|" +
curAlpha + "|" +
origQry;
Session["PrevState"] = tmp;
}
public void LoadStates()
{
string tmp = (string)Session["PrevState"];
if (tmp == null)
{
return;
}
string[] arr = tmp.Split(new char[] { '|' });
sqry = arr[0];
scolumn = arr[1];
keyword = arr[2];
GridView1.SelectedIndex = Convert.ToInt32(arr[3]);
GridView1.PageIndex = Convert.ToInt32(arr[4]);
ddStatus.SelectedIndex = Convert.ToInt32(arr[5]);
curAlpha = arr[6];
origQry = arr[7];
}
void loadECD(string _idno)
{
SaveStates();
Response.Redirect("~/ECDMain.aspx?i=" + _idno);
}
protected void btnbacksearch_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
protected void btnGenerateSF_Click(object sender, EventArgs e)
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=ALL&EmpIDs=" + GetEmpID());
}
private string GetEmpID()
{
string temp = ""; string empIDs = "";
foreach (GridViewRow gRow in GridView1.Rows)
{
temp = GridView1.DataKeys[gRow.RowIndex].Value.ToString();
empIDs = (empIDs == "" ? empIDs : empIDs + ",") + temp;
}
return "(" + empIDs + ")";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && keyword !="")
e.Row.Cells[5].Text = e.Row.Cells[5].ToString().Replace(keyword,"<span style=//background-color: #FFFF00;//>" + keyword + "</span>");
}
public string HighlightText(string InputTxt)
{
// This function is called whenever text is displayed in the FirstName and LastName
// fields from our database. If we're not searching then just return the original
// input, this speeds things up a bit
if (string.IsNullOrEmpty(keyword))
{
return InputTxt;
}
else
{
// Otherwise create a new regular expression and evaluate the FirstName and
// LastName fields against our search string.
Regex ResultStr = default(Regex);
ResultStr = new Regex(keyword.Replace(" ", "|"), RegexOptions.IgnoreCase);
return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));
}
}
public string ReplaceWords(Match m)
{
// This match evaluator returns the found string and adds it a CSS class I defined
// as 'highlight'
return "<span class=highlight>" + m.ToString() + "</span>";
}
//protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
//{
// if ((e.Row.RowType == DataControlRowType.DataRow))
// {
// //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
// ((LinkButton)e.Row.FindControl("lnkResume")).Attributes.Add("onclick", "javascript:OpenFile('" + GridView1.DataKeys[e.Row.RowIndex].Value + "-" + keyword + "')");
// }
//}
protected void btnGenWord_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridViewExportUtil.ExportWord("ReportResultsPage.doc", this.GridView1);
GridView1.AllowPaging = true;
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
BindData();
}
protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e)
{
sqry = sqry + " and i.lastname like '" + curAlpha + "%'";
BindData();
}
}
Please can someone help me. Thanks in advance
You need to rebind the gridview after using the RemoveAt()
GridView1.Columns.RemoveAt(0);
GridView1.DataBind();
When user clicks on export to excel you can disable the delete button, export it and re-enable once exported
GridView1.AutoGenerateDeleteButton = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");

Resources