Link to home
Start Free TrialLog in
Avatar of skaleem1
skaleem1Flag for Canada

asked on

Changing the visibility style of the html button in C# code behind

I have an html button that I want to hide or display when certain condition is met. However, the following line of code in the code behind is completely ignored and the button is still displayed.

this.btnDelete.Style.Remove("visibility");

Please see the code section. Can you see what else is going wrong/missing here?
ASPX:

<button id="btnDelete" type="button" runat="server"  style="height:44px;width:51px;visibility:visible;"
           onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>

Code behind:
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Style.Remove("visibility");
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
                this.btnDelete.Style.Add("visibility", "visible");
}

Open in new window

Avatar of Alpesh Patel
Alpesh Patel
Flag of United States of America image



this.btndelete.visible=False;

or


this.btndelete.visible=True;
don't remove the style, try the followinng
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Visible = false;
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
                this.btnDelete.Visible = true;
}

Open in new window

Avatar of skaleem1

ASKER

I tried to use the btnDelete.Visible property but this seems to be ignored i.e. the button is still visible.
use

            btnDelete.Style.Value = "height:44px;width:51px;display:none;"
for visible

            btnDelete.Style.Value = "height:44px;width:51px;display:;"
for hidden
try to debug your code properly and check your logic on postback, btndelete might get re-load again with default state.

I tried something on test page and it work with btndelete.visible property.
also

btnDelete.Visible = false

works fine. but makes button not rendered, and you cannot use js on client side to make it visible...
make sure this code runs every time
if it is in

If Not Page.IsPostBack Then
...
End If

move it from inside of this code block to outside...
I changed the code as suggested by HainKurt (see code section). I debugged and made sure that the values for btnDelete.Style.Value are correctly assigned. I also made sure that the methois runs regardless of post back or not. Still not working. Any clues?
code behind:

bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
               btnDelete.Style.Value= "height:44px;width:51px;display:none;";                                
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
       btnDelete.Style.Value = "height:44px;width:51px;display:;";
}

aspx:

<button id="btnDelete" type="button" runat="server"  style="height:44px;width:51px;visibility:visible;"
           onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>

Open in new window

Try this
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Style.Add("display", "none");
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
                this.btnDelete.Style.Add("display", "block");
}

Open in new window

not working means "button is not shown on page" or "button is on page"

btnDelete.Style.Value= "height:44px;width:51px;display:none;";

makes button invisible on rendered page

btnDelete.Style.Value = "height:44px;width:51px;display:;";

makes button visible on rendered page

one of them should work depending on value of blnIsMyPortFolio... change the width height values so you can see on page

btnDelete.Style.Value = "height:444px;width:51px;display:;";

for example, it should be biiiiig button ;) if blnIsMyPortFolio is true
The button is always shown/visible on the page regardless of the value of blnIsMyPortFolio. I debugged and found out that it correctly goes to the if-else block depending upon the blnIsMyPortFolio value. So the if-else logic is working. However someohow it only takes the btnDelete.Style.Value = "height:444px;width:51px;display:;"; correctly and displays the button. In the other case when the blnIsMyPortFolio is false, the code goes to the if code block and even sets the btnDelete.Style.Value correctly. However it does not hide the button. I hope that clarifies my point.
masterpass:

I tried your logic but it still fails to hide the button. In the else block, it displays the button and the other buttons are moved and up and down of this button, a behaviour not required. Therefore the following line of code works better in the else block to display the button:

btnDelete.Style.Value = "height:44px;width:51px;display:;";
then we need to see the html...
In that case can you try this too
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Style.Add("visibility", "hidden");
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
                this.btnDelete.Style.Add("visibility", "visible");
}

Open in new window

For the else block, the related block of html is:

<button id="ctl00_ContentPlaceHolder1_btnDelete" type="button" style="height:44px;width:51px;display:;" onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>

For the if block, it's the same, that's wierd. I made sure during debugging that the style for the button is updated to display:none. Any clues?

<button id="ctl00_ContentPlaceHolder1_btnDelete" type="button" style="height:44px;width:51px;display:;" onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>
Can you try my post and tell the results too ?
I guess you are looping and setting the properties of the same button...
masterpass,

I have already tried this one before without success:

btnDelete.Style.Add("visibility", "hidden");
looping, where?
can you please post the whole code... the problem is something else... most of the code posted here should work otherwise...
buttonName.Visible = true/false;
HainKurt

thats what i told skaleem1 to do debug and check where is the state of button gets overwrite......

skaleem1

first of all debug your code and check if it is passes the btndelete.visible=true/false.
if it will give u exception at this moment then it is problem with your current html button access .

if not then you must check your code somewhere it is overwriting the state of btndelete during roundtrip or postback
see below (aspx):
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" MasterPageFile="~/MasterPage.master" CodeBehind="Portfolios.aspx.cs" Inherits="AccessoriesDBAppSolution.Portfolios" validateRequest="false"%>
<%@MasterType VirtualPath="~/MasterPage.master" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <head id="Head1">
    <title>GridView Data Manipulation</title>
    <script type="text/javascript" language="javascript" src="js/wz_tooltip.js"></script>
    <script type="text/javascript">
    
     //Gets the browser specific XmlHttpRequest Object
        function getXmlHttpRequestObject() 
        {	
            if (window.XMLHttpRequest) 
            {		
                return new XMLHttpRequest(); //Not IE	
            } 
            else if(window.ActiveXObject) 
            {		
                return new ActiveXObject("Microsoft.XMLHTTP"); //IE	
            } 
            else 
            {		
                //Display your error message here and inform the user they might want to upgrade their browser.		
                alert("Your browser doesn't support the XmlHttpRequest object.  Better upgrade your browser.");	
            }
         }
         
         //Get our browser specific XmlHttpRequest object.
         var receiveReq;
         //alert(receiveReq);
         var DataReturned;
         var AjaxSecondCallCompleted="False";
         var response;
         var HiddenIsMyPortFolio="False";
         
        function pageLoad(sender,args) 
        { 
            var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>').value;            
            if(HiddenFlag=="")
                TriggerAjaxCall();
            
        }
        
        function TriggerAjaxCall() 
        {            
            if(AjaxSecondCallCompleted=="True")
                    AjaxSecondCallCompleted="False"
            DataReturned="AllParts";
            getPortfolioParts();
        }
        
        
         function getPortfolioParts() 
         {
         receiveReq = getXmlHttpRequestObject();
            switch(DataReturned)
            {
            case "AllParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;                
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) + "&rnd=" + Math.random();                
                break;
            case "CurrentPortfolioParts":
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) + "&rnd=" + Math.random();                
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
            }  
            
            
             receiveReq.abort();
             receiveReq.open("GET", url, true);
             
             receiveReq.onreadystatechange = updatePage;
             receiveReq.send(null);
         }
         
         

       function updatePage() 
       {
         if (receiveReq.readyState == 4) 
         {
           if (receiveReq.status == 200) 
           {
            switch(DataReturned)
                {
                case "AllParts":
                    var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
                    break;
                case "CurrentPortfolioParts":
                    var elSel = document.getElementById('<% =lstPortfolioParts.ClientID%>'); 
                    break;
                default:
                    //code to be executed if DataReturned is different from case 1 and 2
                }
                
                response = receiveReq.responseText;
                
                elSel.outerHTML = elSel.outerHTML.substring(0, elSel.outerHTML.indexOf('>', 0) + 1) + response + '</select>';
                
                
                if(AjaxSecondCallCompleted=="False")
                {
                    AjaxSecondCallCompleted="True"
                    receiveReq = getXmlHttpRequestObject();
                    DataReturned="CurrentPortfolioParts";
                    getPortfolioParts();                    
                }            
           } 
          else
             alert("status is " + receiveReq.status);
         }
       }
       
       var Sender;
        var E;
        var RenameFlag;
        
       function fnClickOK(sender, e, Flag, UserLogin, IsPrivate) 
       {
            Sender=sender;
            E=e;
            ProcessFlag=Flag;
            
            var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
            
            switch(Flag)
            {
            case "Rename":
                DataReturned="PortfolioExist";
                var RenamedPortfolio = document.getElementById('<% =txtRenamePortfolioName.ClientID %>').value;
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                ProcessPortfolioExist(CurrentPortfolio, RenamedPortfolio, UserLogin, IsPrivate);               
                break;
            case "CopyAvailNames":
                DataReturned="PortfolioExistCopyAvailNames";
                //var CopiedPortfolio = document.getElementById('<% =txtCopyPortfolioName.ClientID %>').value;
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                ProcessPortfolioExist(CurrentPortfolio, "", UserLogin, IsPrivate);               
                break;
            case "Copy":
                DataReturned="PortfolioExistCopy";
                var CopiedPortfolio = document.getElementById('<% =txtCopyPortfolioName.ClientID %>').value;
                var CurrentPortfolio = document.getElementById('<% =ddlPortfolios.ClientID %>').value;
                ProcessPortfolioExist(CurrentPortfolio, CopiedPortfolio, UserLogin, IsPrivate);               
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2               
               HiddenFlag.value=Flag;
                __doPostBack(sender,e);
            }
       }
       
       function ProcessPortfolioExist(CurrentPortfolio, Portfolio, UserLogin, IsPrivate) 
       {
            switch(DataReturned)
            {
            case "PortfolioExist":
                receiveReq = getXmlHttpRequestObject();
            
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) + "&RenamedPortfolio=" + escape(Portfolio) + "&UserLogin=" + escape(UserLogin) +  "&IsPrivate=" + escape(IsPrivate) + "&rnd=" + Math.random();                
                //alert(url);
                receiveReq.abort();
                receiveReq.open("GET", url, true);

                receiveReq.onreadystatechange = CheckPortfolioExist;
                receiveReq.send(null);           
                break;
            case "PortfolioExistCopyAvailNames":
               receiveReq = getXmlHttpRequestObject();
            
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio) + "&UserLogin=" + escape(UserLogin) +  "&IsPrivate=" + escape(IsPrivate) + "&rnd=" + Math.random();                
                //alert(url);
                receiveReq.abort();
                receiveReq.open("GET", url, true);

                receiveReq.onreadystatechange = CheckPortfolioExist;
                receiveReq.send(null);          
                break;
            case "PortfolioExistCopy":
               receiveReq = getXmlHttpRequestObject();
            
                var url = "AjaxDBConnectHandler.ashx?DataReturned=" + escape(DataReturned) + "&CurrentPortfolio=" + escape(CurrentPortfolio)  + "&CopiedPortfolio=" + escape(Portfolio) +  "&UserLogin=" + escape(UserLogin) +  "&IsPrivate=" + escape(IsPrivate) + "&rnd=" + Math.random();                
                //alert(url);
                receiveReq.abort();
                receiveReq.open("GET", url, true);

                receiveReq.onreadystatechange = CheckPortfolioExist;
                receiveReq.send(null);          
                break;
            default:
                //code to be executed if DataReturned is different from case 1 and 2
               
            }
            
       }
       
       function CheckPortfolioExist() 
       {
         if (receiveReq.readyState == 4) 
         {
           if (receiveReq.status == 200) 
           {           
                response = receiveReq.responseText;
                switch(DataReturned)
                {
                case "PortfolioExist":
                    if(response=="False")
                    {        
                        var lblRenameError=document.getElementById('<% =lblRenameErrorMessage2.ClientID %>');
                        lblRenameError.style.display = "block";
                        lblRenameError.style.color='red'
                        lblRenameError.innerHTML = "This portfolio name is already in use...";
                        
                        var modalPopupBehaviorCtrl = $find('ModalPopupRename');
                        modalPopupBehaviorCtrl.show();
                    
                    }
                    else if(response=="True")
                    {
                        var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                        HiddenFlag.value=ProcessFlag;
                        __doPostBack(Sender,E);
                    }
                    break;
                case "PortfolioExistCopyAvailNames":
                //alert("I am in PortfolioExistCopy");
                //alert(response);
                   if(response=="False")
                    {        
                        var lblCopyError=document.getElementById('<% =lblCopyErrorMessage2.ClientID %>');
                        lblCopyError.style.display = "block";
                        lblCopyError.style.color='red'
                        lblCopyError.innerHTML = "This portfolio name is already in use...";
                        
                        var modalPopupBehaviorCtrl = $find('ModalPopupCopy');
                        modalPopupBehaviorCtrl.show();                    
                    }
                    else
                    {
                        var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                        HiddenFlag.value=ProcessFlag;
                        
                        var CopyPortfolioName=document.getElementById('<% =txtCopyPortfolioName.ClientID %>');
                        CopyPortfolioName.value = response;
                        var modalPopupBehaviorCtrl = $find('ModalPopupCopy');
                        modalPopupBehaviorCtrl.show();
                        document.getElementById('<% =txtCopyPortfolioName.ClientID %>').focus();
                        document.getElementById('<% =txtCopyPortfolioName.ClientID %>').select();
                        //__doPostBack(Sender,E);
                    }        
                    break;
                case "PortfolioExistCopy":
                //alert("I am in PortfolioExistCopy");
                //alert(response);
                   if(response=="False")
                    {        
                        var lblCopyError=document.getElementById('<% =lblCopyErrorMessage2.ClientID %>');
                        lblCopyError.style.display = "block";
                        lblCopyError.style.color='red'
                        lblCopyError.innerHTML = "This portfolio name is already in use...";
                        
                        var modalPopupBehaviorCtrl = $find('ModalPopupCopy');
                        modalPopupBehaviorCtrl.show();                    
                    }
                    else
                    {
                        var HiddenFlag=document.getElementById('<% =HFlag.ClientID %>');
                        HiddenFlag.value=ProcessFlag;
                        
                        __doPostBack(Sender,E);
                    }        
                    break;
                default:
                    //code to be executed if DataReturned is different from case 1 and 2
                   
                }
                //alert(response);
                
           } 
          else
             alert("status is " + receiveReq.status);
         }
       }


    //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
        
        function showConfirm(source)
        {
            var ConfirmMessage=document.getElementById('<% =lblConfirmMessage.ClientID %>');
            
            var HiddenPartNumberForSelectedGridviewRow=document.getElementById('<% =HPartNumberForGridviewRow.ClientID %>');
            ConfirmMessage.innerHTML="Are you sure you want to delete part " + HiddenPartNumberForSelectedGridviewRow.value + " from the current portfolio?";
            //alert(ConfirmMessage.innerHTML);            
            this._source = source;
            this._popup = $find('mdlPopupConfirmDelete');
            
            //  find the confirm ModalPopup and show it    
            this._popup.show();
            
        }
        
        function okClick(){
            //  find the confirm ModalPopup and hide it    
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, '');
        }
        
        function cancelClick(){
            //  find the confirm ModalPopup and hide it 
            this._popup.hide();
            //  clear the event source
            //this._source = null;
            this._popup = null;
            return true;
        }
        
        function cancelClickRename()
        {
            var lblRenameError=document.getElementById('<% =lblRenameErrorMessage2.ClientID %>');
            lblRenameError.style.display = 'none';
            lblRenameError.innerHTML = "";
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('ModalPopupRename');
            modalPopupBehaviorCtrl.hide();
            //  clear the event source
            //this._source = null;
            modalPopupBehaviorCtrl = null;
            return true;
        }
        
        function cancelClickCopy()
        {
            var lblCopyError=document.getElementById('<% =lblCopyErrorMessage2.ClientID %>');
            lblCopyError.style.display = 'none';
            lblCopyError.innerHTML = "";
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('ModalPopupCopy');
            modalPopupBehaviorCtrl.hide();
            //  clear the event source
            //this._source = null;
            modalPopupBehaviorCtrl = null;
            return true;
        }        
    
        
        function cancelClickConfirmDelete()
        {
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('mdlPopupConfirmDelete');
            modalPopupBehaviorCtrl.hide();
            //  clear the event source
            //this._source = null;
            modalPopupBehaviorCtrl = null;
            return true;
        }
        
        function cancelClickConfirmDeletePortfolio()
        {
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('mdlPopupConfirmDeletePortfolio');
            modalPopupBehaviorCtrl.hide();
            //  clear the event source
            //this._source = null;
            modalPopupBehaviorCtrl = null;
            return true;
        }
        
        function cancelClickCompat()
        {
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('ModalPopupCompat');
            modalPopupBehaviorCtrl.hide();
            //  clear the event source
            //this._source = null;
            modalPopupBehaviorCtrl = null;
            return true;
        }
        
        function cancelClickAddPartToPortfolio()
        {
            //  find the confirm ModalPopup and hide it
            var modalPopupBehaviorCtrl = $find('ModalPopupAddPartToPortfolio');
            modalPopupBehaviorCtrl.hide();
            
            modalPopupBehaviorCtrl = null;
            return true;
        }
        
        
        
        
        var clientid;
        function fnSetFocus(txtClientId)
        {
        	clientid=txtClientId;
        	setTimeout("fnFocus()",100);
            
        }
  
        function fnFocus()
        {
            eval("document.getElementById('"+clientid+"').focus()");
            eval("document.getElementById('"+clientid+"').select()");
        }
 
        var _popupAddPart;
        function ShowPopupAddPartToPortfolio(PopupBehaviorID)
        {
            this._popupAddPart = $find('ModalPopupAddPartToPortfolio');
            this._popupAddPart.show();            
        }
        
        function FindAvailablePortfolioName()
        {
              var HiddenUserLogin=document.getElementById('<% =HUserLogin.ClientID %>').value;
              var HiddenIsPublic=document.getElementById('<% =HIsPublic.ClientID %>').value;
              var HiddenBtnCopyUniqueID=document.getElementById('<% =HBtnCopyUniqueID.ClientID %>').value;
              
              fnClickOK(HiddenBtnCopyUniqueID, "", "CopyAvailNames", HiddenUserLogin, HiddenIsPublic) 
              
                
        }


    function ShowPopup(PopupBehaviorID)
        {
            var modalPopupBehaviorCtrl = $find(PopupBehaviorID);
            modalPopupBehaviorCtrl.show();
            return false;
        }
        
        function rowSelected( AccId, PartNumber )
            {
                //alert( AccId + ' clicked!');
                var HiddenPartIDForSelectedGridviewRow=document.getElementById('<% =HPartIDForGridviewRow.ClientID %>');
                var HiddenPartNumberForSelectedGridviewRow=document.getElementById('<% =HPartNumberForGridviewRow.ClientID %>');
                HiddenPartIDForSelectedGridviewRow.value=AccId;
                HiddenPartNumberForSelectedGridviewRow.value=PartNumber;
                //alert(PartNumber);
                var ConfirmMessage=document.getElementById('<% =lblConfirmMessage.ClientID %>');
                var HiddenDeleteWarningMessage=document.getElementById('<% =HDeleteWarningMessage.ClientID %>');
                
                HiddenDeleteWarningMessage.value="Are you sure you want to delete " + PartNumber + " selected part from the current portfolio?";
                //lblConfirmMessage.text="Are you sure you want to delete " + PartNumber + " selected part from the current portfolio?";
                //alert(ConfirmMessage.text);
            }
            
            var previousRow;
        
        function ChangeRowColor(row)
        {
            //If last clicked row and the current clicked row are same
            if (previousRow == row)
                return;//do nothing
            //If there is row clicked earlier
            else if (previousRow != null)
                //change the color of the previous row back to white
                document.getElementById(previousRow).style.backgroundColor = "#ffffff";
            
            //change the color of the current row to light yellow

            document.getElementById(row).style.backgroundColor = "yellow";            
            //assign the current row id to the previous row id 
            //for next row to be clicked
            previousRow = row;
            
            var DeletePartButton=document.getElementById('<% =btnDeletePart.ClientID %>');
            DeletePartButton.disabled=false;
        }

      
              
        function AddItem(selectbox, text, value ) 
        {            
          var optn = document.createElement("option");
          optn.text = text;
          optn.value = value;
        
         if((selectbox=='ctl00_ContentPlaceHolder1_lstAllComp') || (selectbox=='lstAllComp'))
          {
            var elSel = document.getElementById('<% =lstAllComp.ClientID%>');
          }
          
          if((selectbox=='ctl00_ContentPlaceHolder1_lstAllParts') || (selectbox=='lstAllParts'))
          {
            //var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
            var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
          }
          
          if((selectbox=='ctl00_ContentPlaceHolder1_lstPortfolioParts') || (selectbox=='lstPortfolioParts'))
          {
             //alert(selectbox + ', ' + text + ', ' + value );
            var elSel = document.getElementById('<% =lstPortfolioParts.ClientID%>');
          }
          
          elSel.add(optn);
          
        }
        
       function RemoveItem(selectbox, text, value ) 
        {   
         
        if((selectbox=='ctl00_ContentPlaceHolder1_lstAllParts') || (selectbox=='lstAllParts'))
          {
             //alert(selectbox + ', ' + text + ', ' + value );
            var elSel = document.getElementById('<% =lstAllParts.ClientID%>');
          }
          
          if((selectbox=='ctl00_ContentPlaceHolder1_lstPortfolioParts') || (selectbox=='lstPortfolioParts'))
          {
             //alert(selectbox + ', ' + text + ', ' + value );
            var elSel = document.getElementById('<% =lstPortfolioParts.ClientID%>');
          }
          
        
       
        var i;
        for (i = elSel.length - 1; i>=0; i--) 
        {
            if (elSel.options[i].text==text) 
            {
                elSel.remove(i);
            }
        } 
          
    }
    
    function sortList(listID) 
    { 
        var isNumeric=false;        
       
        if((listID=='ctl00_ContentPlaceHolder1_lstAllParts') || (listID=='lstAllParts'))
          {
            var selectBox = document.getElementById('<% =lstAllParts.ClientID%>');
          }
          
          if((listID=='ctl00_ContentPlaceHolder1_lstPortfolioParts') || (listID=='lstPortfolioParts'))
          {
            var selectBox = document.getElementById('<% =lstPortfolioParts.ClientID%>');         
          }
        
        
        var selectArray = new Array();     
        try 
        { 
            for (i = 0; i < selectBox.length; i++) 
            { 
                selectArray[i] = new Array(); 
                selectArray[i][0] = selectBox.options[i].text; 
                selectArray[i][1] = selectBox.options[i].value; 
                isNumeric=(!isNumeric?!isNaN((selectBox.options[i].text*1)):isNumeric)
            } 
            if (isNumeric) 
            {   
                if((listID=='ctl00_ContentPlaceHolder1_lstAllParts') || (listID=='lstAllParts') || (listID=='ctl00_ContentPlaceHolder1_lstPortfolioParts') || (listID=='lstPortfolioParts'))
                  {
                    selectArray.reverse();
                  }
                else
                {    
                    for (i = 0; i < selectBox.length-1; i++) 
                    { 
                        for (j=i; j < selectBox.length; j++) 
                        { 
                            if( (selectBox.options[i].text*1)>(selectBox.options[j].text*1)) 
                            { 
                                tNum=selectBox.options[i].text; 
                                tVal=selectBox.options[i].Value; 
                                selectBox.options[i].text=selectBox.options[j].text 
                                selectBox.options[i].Value=selectBox.options[j].value 
                                selectBox.options[j].text=tNum; 
                                selectBox.options[j].value=tVal; 
                            } 
                        } 
                    } 
                }
            } 
            else 
            { 
                if((listID=='ctl00_ContentPlaceHolder1_lstAllParts') || (listID=='lstAllParts') || (listID=='ctl00_ContentPlaceHolder1_lstPortfolioParts') || (listID=='lstPortfolioParts'))
                    selectArray.sort(); 
                else
                    selectArray.sort();
                    
                for (j = 0; j < selectBox.length; j++) 
                { 
                    selectBox.options[j].text = selectArray[j][0]; 
                    selectBox.options[j].value = selectArray[j][1]; 
                } 
            } 
        } 
        catch(e) 
        { 
            //In case of any error, dont do anything. 
            alert('The following error occurred: ' + e.name + ' - ' + e.message); 
        } 
    } 
        
        function addSelectedItemToDestAndRemoveFromSource(btnSource, btnDestination, lstSource, lstDestination)
        {   
            switch(btnSource)
            {
            case "btnlstItemAddPartToPortfolioAdd":
              var btnSrc=document.getElementById('<% =btnlstItemAddPartToPortfolioAdd.ClientID%>');
              break;
            case "btnlstItemAddPartToPortfolioRemove":
              var btnSrc=document.getElementById('<% =btnlstItemAddPartToPortfolioRemove.ClientID%>');
              break;
            default:
              //code to be executed if btnSource is different from case 1 and 2
            }
            
            switch(btnDestination)
            {
            case "btnlstItemAddPartToPortfolioAdd":
              var btnDest=document.getElementById('<% =btnlstItemAddPartToPortfolioAdd.ClientID%>');
              break;
            case "btnlstItemAddPartToPortfolioRemove":
              var btnDest=document.getElementById('<% =btnlstItemAddPartToPortfolioRemove.ClientID%>');
              break;
            default:
              //code to be executed if btnSource is different from case 1 and 2
            }
        
            switch(lstSource)
            {
            case "lstAllComp":
                var elSource=document.getElementById('<% =lstAllComp.ClientID%>');
                break;
            case "lstAllParts":
                var elSource=document.getElementById('<% =lstAllParts.ClientID%>');
                break;
            case "lstPortfolioParts":
                var elSource=document.getElementById('<% =lstPortfolioParts.ClientID%>');
                break;
            default:
                //code to be executed if lstSource is different from case 1 and 2
            }
            
            switch(lstDestination)
            {
            case "lstAllParts":
                var elDestination=document.getElementById('<% =lstAllParts.ClientID%>');
                break;
            case "lstPortfolioParts":
                var elDestination=document.getElementById('<% =lstPortfolioParts.ClientID%>');
                break;
            default:
                //code to be executed if lstSource is different from case 1 and 2
            }            
            
            //Store the selected Countries from the lstAllParts htmlSelect listbox into an array to later use it
            //to select those countries in the lstPortfolioParts htmlSelect listbox
            var lstSourceSelectedItemsArray = new Array();
            try 
            { 
                for (i = 0; i < elSource.length; i++) 
                { 
                    if(elSource.options[i].selected)
                    {
                        lstSourceSelectedItemsArray[i] = new Array(); 
                        lstSourceSelectedItemsArray[i][0] = elSource.options[i].text; 
                        lstSourceSelectedItemsArray[i][1] = elSource.options[i].value;
                    }
                }
                
                var isSelected;
                isSelected=false;

                for (i = elSource.length - 1; i>=0; i--) 
                {
                    if (elSource.options[i].selected) 
                    {                
                        isSelected=true;
                        AddItem(lstDestination, elSource.options[i].text, elSource.options[i].value)
                                  
                        elSource.remove(i);                         
                    }
                }
                
                if(!isSelected)
                {
                    alert('Please select an item from the listbox and try again');
                    return;
                }
                else
                    isSelected=true;  
                
                //alert(lstSource + ', ' + lstDestination);
                sortList(lstSource);
                sortList(lstDestination);

                //This for loop takes all the Countries names stored in the lstCountriesArray array
                //and make them selected in the lstCountriesofOrigin htmlSelect Listbox 
                for (j =0; j<elDestination.length; j++) 
                {
                  for (i in lstSourceSelectedItemsArray) 
                  { 
                    if(lstSourceSelectedItemsArray[i][0]==elDestination.options[j].text)
                        elDestination.options[j].selected = true;
                  }
                }
                
                btnSrc.disabled=true;
                btnDest.disabled=false;      
                
                //Store the items from the elDestination htmlSelect listbox into an array to later store it
                //to a hidden variable to retrieve values on server side when required for saving
                if(lstDestination=="lstPortfolioParts")
                {            
                    var lstDestinationSelectedItemsArray = new Array();
                    for (i = 0; i < elDestination.length; i++) 
                    { 
                        lstDestinationSelectedItemsArray[i] = new Array();
                        lstDestinationSelectedItemsArray[i][0] = elDestination.options[i].text; 
                        lstDestinationSelectedItemsArray[i][1] = elDestination.options[i].value;
                    }                
                }
                
                //Store the items from the lstSource htmlSelect listbox into an array to later store it
                //to a hidden variable to retrieve values on server side when required for saving
                if(lstSource=="lstPortfolioParts")
                {            
                    var lstDestinationSelectedItemsArray = new Array();
                    for (i = 0; i < elSource.length; i++) 
                    { 
                        lstDestinationSelectedItemsArray[i] = new Array();
                        lstDestinationSelectedItemsArray[i][0] = elSource.options[i].text;                    
                        lstDestinationSelectedItemsArray[i][1] = elSource.options[i].value;
                    }                
                }       
                
                if(lstDestinationSelectedItemsArray.length>0)
                { 
                    var HiddenDestArray=document.getElementById('<% =HDestArray.ClientID %>');  
                    var savedstring = "";
                    for(i = 0; i < lstDestinationSelectedItemsArray.length; i++)
                    {
                        if(i == lstDestinationSelectedItemsArray.length-1)
                            savedstring = savedstring +  lstDestinationSelectedItemsArray[i][1];
                        else
                            savedstring = savedstring +  lstDestinationSelectedItemsArray[i][1] + ",";
                    }
                    
                    HiddenDestArray.value = savedstring;
                }
            } 
            catch(e) 
            { 
                //In case of any error, dont do anything. 
                if ((e.name=="TypeError") && (e.message=="'length' is null or not an object"))
                    alert('Please select an item from the listbox and try again');
                else
                    alert(e.message);
            } 
        }
        
       
              
    
       function OnChange(btnSource, btnDestination, lstSource, lstDestination)
        {        
            switch(btnSource)
            {
            case "btnlstItemAddPartToPortfolioAdd":
              var btnSrc=document.getElementById('<% =btnlstItemAddPartToPortfolioAdd.ClientID%>');
              break;
            case "btnlstItemAddPartToPortfolioRemove":
              var btnSrc=document.getElementById('<% =btnlstItemAddPartToPortfolioRemove.ClientID%>');
              break;
            default:
              //code to be executed if btnSource is different from case 1 and 2
            }
            
            switch(btnDestination)
            {
            case "btnlstItemAddPartToPortfolioAdd":
              var btnDest=document.getElementById('<% =btnlstItemAddPartToPortfolioAdd.ClientID%>');
              break;
            case "btnlstItemAddPartToPortfolioRemove":
              var btnDest=document.getElementById('<% =btnlstItemAddPartToPortfolioRemove.ClientID%>');
              break;
            default:
              //code to be executed if btnSource is different from case 1 and 2
            }
        
            switch(lstSource)
            {
            case "lstAllComp":
                var elSource=document.getElementById('<% =lstAllComp.ClientID%>');
                break;
            case "lstAllParts":
                var elSource=document.getElementById('<% =lstAllParts.ClientID%>');
                break;
            case "lstPortfolioParts":
                var elSource=document.getElementById('<% =lstPortfolioParts.ClientID%>');
                break;
            default:
                //code to be executed if lstSource is different from case 1 and 2
            }
            
            switch(lstDestination)
            {
            case "lstAllParts":
                var elDestination=document.getElementById('<% =lstAllParts.ClientID%>');
                break;
            case "lstPortfolioParts":
                var elDestination=document.getElementById('<% =lstPortfolioParts.ClientID%>');
                break;
            default:
                //code to be executed if lstSource is different from case 1 and 2
            }
            
            if(lstSource=="lstAllComp")
            {
                var HiddenSelectedListBoxItem=document.getElementById('<% =HSelectedListBoxItem.ClientID %>');
                HiddenSelectedListBoxItem.value="";
                i=0;
                
                var lstSelectedItemsArray = new Array();            
                
                //Store the selected item from the listBox htmlSelect listbox into an array and then store it
                //to a hidden variable to retrieve values on server side when required for saving
                if(lstSource=="lstAllComp")
                {  
                    for (i = 0; i < elSource.length; i++) 
                    { 
                        if (elSource.options[i].selected) 
                        { 
                            var savedstring = "";
                            lstSelectedItemsArray[i] = new Array();
                            lstSelectedItemsArray[i][0] = elSource.options[i].text;                    
                            lstSelectedItemsArray[i][1] = elSource.options[i].value;
                            savedstring= elSource.options[i].value;
                            break;
                        
                        }
                    }                
                }
                
                HiddenSelectedListBoxItem.value = savedstring;
            }
            else
            {
                btnSrc.disabled=false;
                btnDest.disabled=true;
                
                
                for (i = 0; i < elDestination.length; i++) 
                { 
                    if(elDestination.options[i].selected)
                    {
                        elDestination.options[i].selected=false;
                    }
                }  
                
                return true;
            
            }
           
        }
        
        function CallPrint( strid, pageMode, PortfolioNm)

        {
        
            hideColumns(pageMode)

            var prtContent = document.getElementById( strid);

            var strFullhtml="<Div>Portfolio: "  + PortfolioNm + " </Div>" +  prtContent.innerHTML;
            //alert(strFullhtml);
            
            var WinPrint = window.open('', '', 'left=0,top=0,width=1000,height=1000,status=0');
            WinPrint.document.write( strFullhtml );
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();

            // prtContent.innerHTML=strOldOne;

        }
        
        function CallPrintUsersGuest( strid, PortfolioNm )

        {
            //In this method we do not call hideColumns method as these Edit/Delete columns are never added
            //for the Users and Guests roles
            var prtContent = document.getElementById( strid );
            
            var strFullhtml="<Div>Portfolio: "  + PortfolioNm + " </Div>" +  prtContent.innerHTML;
            
            var WinPrint = window.open('', '', 'left=0,top=0,width=1000,height=1000,status=0');
            WinPrint.document.write( strFullhtml );
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
        }
        
       function hideColumns(pageMode)
        {                    
            var gridViewCtlId = '<%=GridViewPortfolio.ClientID%>'; 
            var gv = document.getElementById(gridViewCtlId); 
            
            //get reference to the rows collection
            rows = gv.rows;
            for(i=0;i <rows.length;i++)
            { 
                //get the reference of each row column count
                if(pageMode==1) //case when only edit button is the first column of the gridview
                {
                    rows[i].cells[0].style.display="none";
                }
                else if(pageMode==2) //case when edit and delete buttons are the first and second columns of the gridview
                {  
                    if (rows[i].cells[0]!=null)                
                        rows[i].cells[0].style.display="none";
                    if (rows[i].cells[1]!=null)  
                        rows[i].cells[1].style.display="none";
                }
                else if(pageMode==3) //case when edit and delete buttons are the last two columns of the gridview
                {
                    Columns=rows[i].cells.length;
                    if (Columns>1)
                    {
                        rows[i].cells[Columns-1].style.display="none";
                        rows[i].cells[Columns-2].style.display="none";
                    }
                }
            }
        }
         


    </script>

    <style type="text/css">
        
      
        .HeaderPartDesc
        {
            width: 700px;
        }
        
                
        
        
        div.OuterListBox {

        width: 500px;
        
        height: 125px;

        border: none;

        position: relative;

        clear: both;

        }
        
        div.OuterListBoxAddToPortfolio {

        width: 500px;
        
        height: 135px;

        border: none;

        position: relative;

        clear: both;

        }
        
        div.InnerLeftListBox {

        width: 70%;

        position: relative;

        background: none;        

        float: left;

        }

 

        div.InnerRightListBox {

        width: 30%;

        position: relative;

        background: none;        

        float: right;
            top: 0px;
            left: 36px;
            height: 80px;
        }
        
        div.InnerRightListBoxAddPartToPortfolio {

        width: 30%;

        position: relative;

        background: none;        

        float: right;
            top: 0px;
            left: 36px;
            height: 90px;
        }
        
        
        div.InnerLeftListBoxRename {

        width: 90%;

        position: relative;

        background: none;        

        float: left;

        }

        
         div.InnerRightListBoxRename {

        width: 10%;

        position: relative;

        background: none;        

        float: right;
            top: 0px;
            left: 36px;
            height: 70px;
        }
        
        .modalBackground
        {
            background-color:#CCCCFF;
            filter:alpha(opacity=40);
            opacity:0.5;
        }
        
        
        .modalBackgroundDelete {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }

        
        .ModalWindow
        {
        	border: solid1px#c0c0c0;
            border-width: 1px;
            border-style: solid; 
            border-color: Gray;

            background:#f0f0f0;
            width: 700px;
        }
        
        .ModalWindowRename
        {
        	border: solid1px#c0c0c0;
            border-width: 1px;
            border-style: solid; 
            border-color: Gray;

            background:#f0f0f0;
            width: 400px;
            height: 150px;
        }
        
         .ModalWindowCopy
        {
        	border: solid1px#c0c0c0;
            border-width: 1px;
            border-style: solid; 
            border-color: Gray;

            background:#f0f0f0;
            width: 400px;
            height: 150px;
        }
        
        table.mylist input[type="radio"]  
        {        	
          width: 20px;
          padding: 0;
          display: block;
          float: left;
          vertical-align: middle; 
        }
        
       table.mylist label 
       {
          width: 250px;
          display: block;
          float: left;
          text-align: left; 
       }

        .confirm{
           background-color:White;
           width:370px;
        }

                
        

    </style>


</head>
<div id="content" runat="server">
        <div id="leftCol" class="leftCol">
            <!-- Left nav tree view goes here -->
            <asp:TreeView ID="leftNavTreeView" runat="server" Visible="false" ShowLines="True" Width="125px">
                <SelectedNodeStyle BackColor="#FFFF66" />
            </asp:TreeView>
        </div>
        <div id="midCol" class="midCol">
        <div>&nbsp
            <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
                        </asp:ToolkitScriptManager>              
            <button id="btnAdd" type="button" runat="server" style="height:44px;width:51px"
                       onclick="ShowPopup('ModalPopupCompat');">Add</button>
            <asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="btnEdit_Click" Enabled="false" Visible="false" Height="44px" Width="51px"/>
            <asp:Button ID="btnNext" runat="server" Text="Next" Visible="false" OnClick="btnNext_Click" Height="44px" Width="51px"/>
            <button id="btnCopy" type="button" runat="server" style="height:44px;width:51px"
             onclick="FindAvailablePortfolioName();">Copy</button>&nbsp            
            <button id="btnDelete" type="button" runat="server"  style="height:44px;width:51px;"
           onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>
            <asp:Button ID="btnUndo" runat="server" Visible="false" Text="Undo" OnClick="btnUndo_Click" Height="44px" Width="51px"/>
            <asp:Button ID="btnRedo" runat="server" Visible="false" Text="Redo" OnClick="btnRedo_Click" Height="44px" Width="51px"/>&nbsp
            <asp:Button ID="btnReports" runat="server" Text="Reports" Visible="false" OnClick="btnReports_Click" Height="44px" Width="51px"/>&nbsp
            <asp:Button ID="btnPrint" runat="Server" Text="Print" OnClick="btnPrint_Click" Height="44px" Width="51px"/>
            <asp:Button ID="btnExport" runat="Server" Text="Export" OnClick="btnExport_Click" Height="44px" Width="51px"/>&nbsp
             &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;                              
            <button id="btnCancel" type="button" runat="server" visible="false" style="height:44px;width:51px">Cancel</button>
            <asp:ModalPopupExtender ID="CompatPanel_ModalPopupExtender" runat="server" 
                        TargetControlID="btnAdd" PopupControlID="CompEditPanelMain"
                        PopupDragHandleControlID="CompTitleBar" BehaviorID="ModalPopupCompat"
                        CancelControlID="btnCompCancel" OnCancelScript="cancelClickCompat();"
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true" >
                    </asp:ModalPopupExtender>
            <asp:ModalPopupExtender ID="ConfirmDeletePortfolioPanel_ModalPopupExtender" BehaviorID="mdlPopupConfirmDeletePortfolio" 
                runat="server" TargetControlID="btnDelete" PopupControlID="DeletePortfolioConfirmPanel"
                PopupDragHandleControlID="DeleteTitleBarPanel" Drag="true"
                CancelControlID="btnNoDeletePortfolio" OnCancelScript="cancelClickConfirmDeletePortfolio();"
                BackgroundCssClass="modalBackgroundDelete">
                </asp:ModalPopupExtender>
            <asp:ModalPopupExtender ID="Copy_ModalPopupExtender" runat="server" 
                        TargetControlID="btnUpdatePanel" PopupControlID="PortfolioCopyPanelMain"
                        PopupDragHandleControlID="CopyTitleBar" BehaviorID="ModalPopupCopy"
                        CancelControlID="btnCopyCancel" OnCancelScript="cancelClickCopy();"
                        OkControlID="btnPopupCopy" OnOkScript="__doPostBack('btnPopupCopy()','')" 
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true">
                    </asp:ModalPopupExtender>
                    <asp:Button ID="btnUpdatePanel" runat="server"
                        OnClick="btnUpdatePanel_Click" style="display:none;"/>             
            <br />
            <asp:TextBox ID="text" runat="server" style="display:none;"></asp:TextBox>
         </div>
        <asp:Panel ID="PartNumberEditReadOnlyPanel" runat="server" Visible="false">
        <div>
            <table border="1">
                <tr><td class="HeaderPartDesc" bgcolor="#3366CC">
                <asp:Label ID="lblPartNumInfoHeader" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Large" Font-Bold="True"></asp:Label>&nbsp;&nbsp;<asp:Label ID="lblPartDescInfoHeader" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td></tr>
            </table>
        </div>
        </asp:Panel>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <fieldset style="width:700px">
        <div>           
            <table><tr><td>
            <asp:Label ID="lblPortfolio" runat="server" Text="Portfolio:"></asp:Label>&nbsp;
            <asp:DropDownList ID="ddlPortfolios" runat="server" Width="192px"></asp:DropDownList>&nbsp;
            <button id="btnRename" type="button" runat="server" style="height:27px;width:61px" disabled="true"
                       onclick="ShowPopup('ModalPopupRename');">Rename</button></td><td style="width:150px"></td>                       
                       <td><asp:ModalPopupExtender ID="Rename_ModalPopupExtender" runat="server" 
                        TargetControlID="btnRename" PopupControlID="PortfolioRenamePanelMain"
                        PopupDragHandleControlID="RenameTitleBar" BehaviorID="ModalPopupRename"
                        CancelControlID="btnRenameCancel" OnCancelScript="cancelClickRename();"
                        OkControlID="btnPopupRename" OnOkScript="__doPostBack('btnPopupRename()','')" 
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true">
                    </asp:ModalPopupExtender></td>
            <td><asp:UpdatePanel ID="UpdatePanelAnimationExtender1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <fieldset style="width:150px">
            <asp:CheckBox ID="chkIsPrivate" runat="server" Text="Portfolio is private" 
                        oncheckedchanged="chkIsPrivate_CheckedChanged"/>                        
                        <br />
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:Label ID="lblPortfolioOwner" runat="server" visible="false" Text="Owner:"></asp:Label>
            </fieldset>
            </ContentTemplate>
            </asp:UpdatePanel></td></tr><tr><td></td><td style="width:150px"></td>
            <td></td></tr></table>            
            </div>
            <br /><br /><br />
            <div><asp:Button ID="btnAddPart" runat="server" Text="Add Part" style="height:23px;width:71px"
                       OnClientClick="ShowPopupAddPartToPortfolio(this); return true;" />
            <asp:Button ID="btnAddCurrentPart" runat="server" Text="Add Current Part" Enabled="false" OnClick="btnAddCurrentPart_Click" />
            <asp:Button ID="btnDeletePart" runat="server" Text="Remove Part" Enabled="false" OnClientClick="showConfirm(this); return true;"/>
            <asp:Label ID="lblRecordCount" runat="server" ForeColor="#990033"></asp:Label>
            <asp:Label ID="lblErrorMessageMain" ForeColor="Red" runat="server" visible="false"/>
            <asp:ModalPopupExtender ID="ConfirmDeletePanel_ModalPopupExtender" BehaviorID="mdlPopupConfirmDelete" 
                runat="server" TargetControlID="btnDeletePart" PopupControlID="DeleteConfirmPanel"
                PopupDragHandleControlID="DeleteTitleBarPanel" Drag="true"
                CancelControlID="btnNo" OnCancelScript="cancelClickConfirmDelete();"
                BackgroundCssClass="modalBackgroundDelete">
                </asp:ModalPopupExtender>
            <asp:ModalPopupExtender ID="AddPartToPortfolioPanel_ModalPopupExtender" runat="server" 
                        TargetControlID="btnAddPart" PopupControlID="AddPartToPortfolioEditPanelMain"
                        PopupDragHandleControlID="AddPartToPortfolioEditTitleBar" BehaviorID="ModalPopupAddPartToPortfolio"
                        CancelControlID="btnAddPartToPortfolioCancel" OnCancelScript="cancelClickAddPartToPortfolio();"                        
                        BackgroundCssClass="modalBackground" DropShadow="true" Drag="true" >
                    </asp:ModalPopupExtender>                   
                </div>                          
        <div id='print_grid'>
            <asp:GridView ID="GridViewPortfolio" runat="server" ShowFooter ="True" 
            OnPageIndexChanging="GridViewPortfolio_PageIndexChanging"
            OnRowUpdating="GridViewPortfolio_RowUpdating" OnRowEditing="GridViewPortfolio_RowEditing"
            OnRowCancelingEdit="GridViewPortfolio_RowCancelingEdit" OnInit="GridViewPortfolio_Init"
            OnRowDeleting="GridViewPortfolio_RowDeleting" OnRowCreated="GridViewPortfolio_RowCreated"
            OnRowDataBound="GridViewPortfolio_RowDataBound" OnSelectedIndexChanged="GridViewPortfolio_SelectedIndexChanged"
                    AllowPaging="False" PageSize="10" AllowSorting="True" AutoGenerateColumns="False"
                    BorderColor="Black" BorderWidth="1px">
                    <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="Yellow" />                    
            </asp:GridView>
            </div>                       
             </fieldset>
            </ContentTemplate>
            </asp:UpdatePanel>       
            <!-------------------------------->
            
            <asp:Panel ID="CompEditPanelMain" runat="server"
                Direction="LeftToRight" CssClass="ModalWindow" style="display:none">
               <asp:Panel ID="CompTitleBar" runat="server">
            <table>
                <tr><td style="text-align: left" class="HeaderPartDesc" bgcolor="#3366CC"> 
                <asp:Label ID="lblTitleBar" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Add New Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label2" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td></tr>
            </table>
        </asp:Panel>
        <div class="OuterListBox">
        <div class="InnerLeftListBox">
         <asp:Panel ID="radioOptionsPanel" runat="server" BorderStyle="Outset">            
            <asp:radiobuttonlist id="radioAddPortfolioOptions" runat="server" RepeatLayout="Table" RepeatDirection="Vertical"
                RepeatColumns="1" CssClass="mylist">
              <asp:listitem id="optHHCompat" runat="server" value="Handheld Compatibility Based Portfolio" Selected="True" />
              <asp:listitem id="optNewPortfolio" runat="server" value="Empty Portfolio" />
            </asp:radiobuttonlist>
            </asp:Panel>
             <asp:Panel ID="PortfolioNmPanel" BorderStyle="Outset" runat="server">
             <table>
                    <tr><td></td></tr>
                    <tr><td><asp:Label ID="lblPortfolioName" runat="server" Text="Portfolio Name" style="text-align: left" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td>
                <td><asp:TextBox ID="txtPortfolioName" runat="server"
                        Width="100px"></asp:TextBox></td></tr>
                    <tr><td><asp:RequiredFieldValidator runat="server" id="reqPortFolioNm" ControlToValidate="txtPortfolioName"
                    ErrorMessage = "You must enter the Portfolio Name!"
                    display="Dynamic" /><asp:Label ID="lblErrorMessage" BackColor="Red" runat="server" visible="false"/></td></tr></table>
            </asp:Panel>         
        </div>
        <div class="InnerRightListBox">
            <asp:Panel ID="CompEditPanelRight" runat="server">
            </asp:Panel>
            <asp:Panel ID="CompAddPanel" runat="server">
                <table style="width: 180px">
                    <tr><td><asp:Label ID="lblAllComp" runat="server" Text="All Handhelds" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td><td style="width: 30px"></td></tr>
                    <tr><td style="width: 150px">
                    <p><select id="lstAllComp" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px"
                    onchange='OnChange("","","lstAllComp","");'>          
                </select></p></td><td><asp:HiddenField ID="HSelectedListBoxItem" runat="server" />
                <asp:HiddenField ID="HPortfolioID" runat="server" />
                <asp:HiddenField ID="HIsPrivate" runat="server" />
                <asp:HiddenField ID="HPartIDForGridviewRow" runat="server" />
                <asp:HiddenField ID="HPartNumberForGridviewRow" runat="server" />
                <asp:HiddenField ID="HDeleteWarningMessage" runat="server" />
                <asp:HiddenField ID="HFlag" runat="server" />
                <asp:HiddenField ID="HDestArray" runat="server" />
                <asp:HiddenField ID="HUserLogin" runat="server" />
                <asp:HiddenField ID="HIsPublic" runat="server" />
                <asp:HiddenField ID="HBtnCopyUniqueID" runat="server" /></td>
                    </tr>
                </table>
                
            </asp:Panel>
        </div></div>
        <br />
       <asp:Button ID="btnCompAdd" runat="server" Text="Add" OnClick="btnCompAdd_Click"/>
       <asp:Button ID="btnCompCancel" runat="server" Text="Cancel" CausesValidation="False"/>
       </asp:Panel>
       
       <asp:Panel ID="PortfolioRenamePanelMain" runat="server"
                Direction="LeftToRight" CssClass="ModalWindowRename" style="display:none">                
               <asp:Panel ID="RenameTitleBar" runat="server">
            <table>
                <tr><td style="text-align: left" class="HeaderPartDesc" bgcolor="#3366CC"> 
                <asp:Label ID="lblRenameTitleBar" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Rename Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label1" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td>
        </tr>
            </table>
        </asp:Panel>
        <asp:UpdatePanel ID="UpdatePanelPortfolioRename" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <fieldset style="width:300px">
        <div class="InnerLeftListBox"> 
             <table>
                    <tr><td></td></tr>
                    <tr><td><asp:Label ID="lblRenamePortfolioName" runat="server" Text="Portfolio Name" 
                    style="text-align: right" Width="130px"
                    ForeColor="#3366CC" Font-Size="Small" Font-Bold="True"/></td><td></td>
                <td><asp:TextBox ID="txtRenamePortfolioName" runat="server" 
                        Width="150px"></asp:TextBox></td></tr>
                    <tr><td><asp:RequiredFieldValidator runat="server" id="reqRenamePortFolioNm" ControlToValidate="txtRenamePortfolioName"
                    ErrorMessage = "You must enter the Portfolio Name!"
                    display="Dynamic" /><asp:Label ID="lblRenameErrorMessage" BackColor="Red" runat="server" visible="false"/>
                    <asp:Label ID="lblRenameErrorMessage1" runat="server" style="display:none"/>
                    <label id="lblRenameErrorMessage2" runat="server" style="display:none"></label>
                    </td></tr>
                    </table>   
        </div>
        </fieldset></ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="ddlPortfolios" EventName="SelectedIndexChanged" />
           </Triggers>
            </asp:UpdatePanel>
            <asp:Button ID="btnPopupRename" runat="server" OnClick="btnPopupRename_Click" style="height:25px;width:61px" Text="Rename" />
       <asp:Button ID="btnRenameCancel" runat="server" Text="Cancel" 
       style="height:25px;width:61px" CausesValidation="False" />       
        <div class="InnerRightListBoxRename">                  
        </div>        
        <br />
       </asp:Panel>
       
       <asp:Panel ID="DeleteConfirmPanel" runat="server" class="confirm" 
            style="display:none;width:420px">
               <asp:Panel ID="DeleteTitleBarPanel" runat="server">
            <table>
                <tr><td style="text-align: left" class="HeaderPartDesc" bgcolor="#3366CC"> 
                <asp:Label ID="lblDeletePartFromPortfolio" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Delete Part from Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label4" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td>
        </tr>
            </table>
        </asp:Panel>
                <div id="div1" runat="server" align="center" class="confirm">
                        <asp:Label ID="lblConfirmMessage" runat="server" Text="Are you sure you want to remove selected part from the current portfolio?"></asp:Label>
                        
                        <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" OnClick="btnOK_Click" />
                        <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" CausesValidation="False"/>
                </div>
                
            </asp:Panel>
            
       <asp:Panel ID="AddPartToPortfolioEditPanelMain" runat="server"
                Direction="LeftToRight" CssClass="ModalWindow" style="display:none">
        <asp:Panel ID="AddPartToPortfolioEditTitleBar" runat="server">
            <table>
                <tr><td style="text-align: left; width:700px" bgcolor="#3366CC"> 
                <asp:Label ID="lblAddPartToPortfolioEditTitleBar" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Add Parts To Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label3" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td></tr>
            </table>
        </asp:Panel>
        <div class="OuterListBoxAddToPortfolio">
        <div class="InnerLeftListBox">
            <table style="width: 260px">
                <tr><td><asp:Label ID="lblForThisPartAddPartToPortfolio" runat="server" Text="Portfolio Parts" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td><td style="width: 30px"></td></tr>
                <tr><td style="width: 150px"><p><select id="lstPortfolioParts" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px" multiple="true" 
                onchange='OnChange("btnlstItemAddPartToPortfolioRemove", "btnlstItemAddPartToPortfolioAdd","lstPortfolioParts", "lstAllParts");'>          
                </select></p></td>
                <td style="width: 80px">
            <button id="btnlstItemAddPartToPortfolioAdd" type="button" runat="server" onclick="addSelectedItemToDestAndRemoveFromSource('btnlstItemAddPartToPortfolioAdd', 'btnlstItemAddPartToPortfolioRemove', 'lstAllParts','lstPortfolioParts');">&lt&ltAdd</button>
            <button id="btnlstItemAddPartToPortfolioRemove" type="button" runat="server" onclick="addSelectedItemToDestAndRemoveFromSource('btnlstItemAddPartToPortfolioRemove', 'btnlstItemAddPartToPortfolioAdd', 'lstPortfolioParts','lstAllParts');">Remove>></button>
            </td></tr>
            </table>
        </div>
        <div class="InnerRightListBoxAddPartToPortfolio">
            <asp:Panel ID="AddPartToPortfolioEditPanelRight" runat="server">
            </asp:Panel>
            <asp:Panel ID="AddPartToPortfolioAddPanel" runat="server">
                <table style="width: 180px">
                    <tr><td><asp:Label ID="lblAllParts" runat="server" Text="All Parts" ForeColor="#3366CC" 
                Font-Size="Small" Font-Bold="True"/></td><td style="width: 30px"></td></tr>
                    <tr><td style="width: 150px">
                    <p><select id="lstAllParts" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px" multiple="true" 
                onchange='OnChange("btnlstItemAddPartToPortfolioAdd", "btnlstItemAddPartToPortfolioRemove","lstAllParts", "lstPortfolioParts");'>          
                </select></p></td>
                    </tr>
                </table>
                
            </asp:Panel>
        </div></div>
        <br />
        <div><div>
       <asp:Button ID="btnAddPartToPortfolioSave" runat="server" Text="Save" OnClick="btnAddPartToPortfolioSave_Click"/>
       <asp:Button ID="btnAddPartToPortfolioCancel" runat="server" Text="Cancel" CausesValidation="False"/>
       </div></div>
       </asp:Panel>
       
       <asp:Panel ID="DeletePortfolioConfirmPanel" runat="server" class="confirm" 
            style="display:none;width:420px">
               <asp:Panel ID="DeletePortfolioTitleBarPanel" runat="server">
            <table>
                <tr><td style="text-align: left" class="HeaderPartDesc" bgcolor="#3366CC"> 
                <asp:Label ID="lblDeletePortfolio" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Delete Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label5" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td>
        </tr>
            </table>
        </asp:Panel>
                <div id="div2" runat="server" align="center" class="confirm">
                        <asp:Label ID="lblConfirmMessageDeletePortfolio" runat="server" Text="Are you sure you want to delete the currently selected portfolio?"></asp:Label>
                        <div>
                        <asp:Button ID="btnOkDeletePortfolio" runat="server" Text="Yes" Width="50px" OnClick="btnOKDeletePortfolio_Click" />
                        <asp:Button ID="btnNoDeletePortfolio" runat="server" Text="No" Width="50px" CausesValidation="False"/>
                </div></div>
                
            </asp:Panel>
            
            <asp:Panel ID="PortfolioCopyPanelMain" runat="server"
                Direction="LeftToRight" CssClass="ModalWindowCopy" style="display:none">                
               <asp:Panel ID="CopyTitleBar" runat="server">
            <table>
                <tr><td style="text-align: left" class="HeaderPartDesc" bgcolor="#3366CC"> 
                <asp:Label ID="lblCopyTitleBar" 
                        runat="server" BackColor="#3366CC" style="text-align: left"
                ForeColor="White" Font-Size="Small" Font-Bold="True" Text="Copy Portfolio"></asp:Label>&nbsp;&nbsp;<asp:Label ID="Label6" 
                        runat="server" BackColor="#3366CC" 
                ForeColor="White" Font-Size="Small"></asp:Label></td>
        </tr>
            </table>
        </asp:Panel>
        <asp:UpdatePanel ID="UpdatePanelPortfolioCopy" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <fieldset style="width:300px">
        <div class="InnerLeftListBox"> 
             <table>
                    <tr><td></td></tr>
                    <tr><td><asp:Label ID="lblCopyPortfolioName" runat="server" Text="Portfolio Name" 
                    style="text-align: right" Width="130px"
                    ForeColor="#3366CC" Font-Size="Small" Font-Bold="True"/></td><td></td>
                <td><asp:TextBox ID="txtCopyPortfolioName" runat="server" 
                        Width="150px"></asp:TextBox></td></tr>
                    <tr><td><asp:RequiredFieldValidator runat="server" id="reqCopyPortFolioNm" ControlToValidate="txtCopyPortfolioName"
                    ErrorMessage = "You must enter the Portfolio Name!"
                    display="Dynamic" /><asp:Label ID="lblCopyErrorMessage" BackColor="Red" runat="server" visible="false"/>
                    <asp:Label ID="lblCopyErrorMessage1" runat="server" style="display:none"/>
                    <label id="lblCopyErrorMessage2" runat="server" style="display:none"></label>
                    </td></tr>
                    </table>   
        </div>
        </fieldset></ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="ddlPortfolios" EventName="SelectedIndexChanged" />
           </Triggers>
            </asp:UpdatePanel>
            <asp:Button ID="btnPopupCopy" runat="server" OnClick="btnPopupCopy_Click" style="height:25px;width:61px" Text="Copy" />
       <asp:Button ID="btnCopyCancel" runat="server" Text="Cancel" 
       style="height:25px;width:61px" CausesValidation="False" />
        <div class="InnerRightListBoxRename">                  
        </div>        
        <br />
       </asp:Panel>
       
       
       </div> <!-- End of Content Div-->       
        
   </div>
</asp:Content>
<asp:Content ID="Content2" runat="server" contentplaceholderid="head">
    <style type="text/css">
        .style1
        {
            width: 651px;
        }
    </style>
    </asp:Content>

Open in new window

see below (code behind):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; 
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AccessoriesApp.Biz.DataGateway;

namespace AccessoriesDBAppSolution
{
    public partial class Portfolios : System.Web.UI.Page
    {
        private string _PartNumber = string.Empty;
        private string _PortFolio = string.Empty;
        string _PortfolioRenamed = string.Empty;
        string _PortfolioCopied = string.Empty;
        private static string _HandheldName = string.Empty;
        DataSet dsPortfolios;
        DataSet dsPartsForCurrentPortfolio;
        DataSet dsDropDownPortfolios;
        private const string FAMILIES = "Families";
        private const string CLANS = "Clans";
        private const string HHFAMILY = "HHFamily";
        private const string MG = "MG";
        private const string HIERARCHY = "Hierarchy";
        private const string PORTFOLIOS = "Portfolios";
        private const string ACCESSORIES = "Accessories";
        private const string COMPATIBILITY = "Compatibility";
        private const string COMPATIBILITYCOLUMNS = "Compatibility";
        private const string COMPATIBILITYHANDHELDCOLUMNS = "CompatibilityHandhelds";
        private const string PORTFOLIOPARTS = "PortFolioParts";
        DataSet dsMaterialHierarchy;
        private string jsMain = string.Empty;
        private string _CalledFrom = string.Empty;

        string _PortfolioIDCurrent;
        bool _isPublicPortfolio = false;
        bool _isPrivatePortfolio = false;
        bool _IsMyPortFolio = true;

        List<KeyValuePair<string, string>> SortedCompatibility;

        public override void VerifyRenderingInServerForm(Control control) { }

       

        protected void Page_Load(object sender, EventArgs e)
        {
            if ((HFlag.Value == "PortfolioPartsAdded") || (HFlag.Value=="DeletePortfolio") || (HFlag.Value=="ExportPortfolio"))
            {
                //Session["dsPortfolios"] = null; //This fill force the data reloaded from the database and the page refreshed with latest data
                //HFlag.Value = "";
                PopulateCompatibilityData();
                return;
            }

            System.Web.UI.HtmlControls.HtmlGenericControl control = Master.BodyTag;

            GetMaterialGroupsHierarchy();
            //EnableEditing();

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            this.HUserLogin.Value= Session["UserLogin"].ToString();
            this.HIsPublic.Value = chkIsPrivate.Checked.ToString();
            this.HBtnCopyUniqueID.Value=btnCopy.UniqueID;
            
            btnOk.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnOk.UniqueID, "", "", "", "");
            btnAddPartToPortfolioSave.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnAddPartToPortfolioSave.UniqueID, "", "PortfolioPartsAdded", "", "");
            btnAddCurrentPart.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnAddCurrentPart.UniqueID, "", "", "", "");
            btnOkDeletePortfolio.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnOkDeletePortfolio.UniqueID, "", "DeletePortfolio", "", "");
            btnExport.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnExport.UniqueID, "", "ExportPortfolio", "", "");
 
            this.btnRename.Attributes.Add("onclick", "fnSetFocus('" + this.txtRenamePortfolioName.ClientID + "');");
            //btnCopy.Attributes.Add("onclick", String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnCopy.UniqueID, "", "Copy", Session["UserLogin"].ToString(), chkIsPrivate.Checked.ToString()));
            //this.btnCopy.Attributes.Add("onclick", "fnSetFocus('" + this.txtCopyPortfolioName.ClientID + "');");
            
            if (!string.IsNullOrEmpty(Request.QueryString["PortfolioNm"]))
            {
                _PortFolio = Request.QueryString["PortfolioNm"];
                Session["CurrentPortfolio"] = _PortFolio;
            }
            
            if (!string.IsNullOrEmpty(Request.QueryString["calledfrom"]))
            {
                _CalledFrom = Request.QueryString["calledfrom"];
            }
            

            chkIsPrivate.AutoPostBack = true;
            RetrieveDataGateway rdg = new RetrieveDataGateway();
         
            if (!IsPostBack)
            {
                bool LoadData = false;
                if (!string.IsNullOrEmpty(Request.QueryString["AccPartNum"]))
                {
                    _PartNumber = Request.QueryString["AccPartNum"];
                    Session["CurrentPart"] = _PartNumber;
                    LoadData = true;
                }       

                if (Session["CurrentPart"] != null)
                    _PartNumber = Session["CurrentPart"].ToString();

                 if (Session["CurrentPortfolio"] != null)
                    _PortFolio = Session["CurrentPortfolio"].ToString();                
                
                if (_PartNumber == "")
                {
                    DataSet dsCurrentPart=null;
                    
                    LoadData = true;
                    
                    if (Session["UserLogin"] != null)
                    {
                        dsCurrentPart = rdg.GetDataInfoByOneParam("GetCurrentPartForCurrentUser", Session["UserLogin"].ToString(), "UserLogin");
                    //dsCurrentPart = rdg.GetDataInfoByOneParam("GetCurrentPortfolioForCurrentUser", Session["UserLogin"].ToString(), "UserLogin");
                    }
                    else
                        Response.Redirect(string.Format("~/Login.aspx"));

                    if (dsCurrentPart.Tables[0].Rows.Count > 0)
                        _PartNumber = dsCurrentPart.Tables[0].Rows[0].ItemArray[0].ToString();
                    else
                        _PartNumber = "ACC-03279-001";                 


                    Session["CurrentPart"] = _PartNumber;
                }
                else 
                {
                    LoadData = false;

                    //Update the UserAccLink table to store the last current part the user was working on if any
                    if (Session["UserLogin"] != null)
                    {
                        rdg.SaveCurrentPartForCurrentUser("SaveCurrentPartForCurrentUser", _PartNumber, Session["UserLogin"].ToString());

                    }
                    else
                        Response.Redirect(string.Format("~/Login.aspx"));
                }                

                DataSet dsMaterialGroupFamily;
                dsMaterialGroupFamily = rdg.GetDataInfoByOneParam("GetMaterialGroupFamilyForCurrentpart", _PartNumber, "PartNum");
                
                RetrieveData(LoadData);

                if (dsPortfolios == null)
                    dsPortfolios = (DataSet)Session["dsPortfolios"];

                if (dsPortfolios.Tables[PORTFOLIOS].Rows.Count > 0)
                {
                    //btnEdit.Enabled = true;
                    AddPortfoliosToDDL();

                    RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));
                }

                lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";

                LoadHeaderControls("ReadOnly");
               
                LoadTreeView();                

                ShowMasterPageLinks();
                jsMain = "";
                rdg.ResetAllPartsAddedDltdUpdtdInfoForCurntUsr("ResetAllPartsAddedDltdUpdtdInfoForCurntUsr", Session["UserLogin"].ToString());                
            }

            btnRename.Disabled = false;
            ddlPortfolios.AutoPostBack = true;
            
            //jsMain = jsMain + "doHourglass();";
            PopulateCompatibilityData();

            if ((HFlag.Value == "") || (HFlag.Value == "PortfolioPartsAdded") || (HFlag.Value == "DeletePortfolio") || (HFlag.Value == "ExportPortfolio"))
            {
                txtRenamePortfolioName.Text = ReturnDDLSelectedItem();
                //txtCopyPortfolioName.Text = ReturnDDLSelectedItem();
                //txtCopyPortfolioName.Text = txtCopyPortfolioName.Text + "_Copy";
            }

            if(dsPortfolios==null)
                dsPortfolios = (DataSet)Session["dsPortfolios"];
            DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            string PortfolioID = ddlPortfolios.SelectedValue.ToString(); // SearchDropDownTextIDFromDataTable(table, ddlPortfolios.SelectedItem.Text, "PortfolioID");

            if (IsPostBack)
            {
                bool PartsAddedDeleted = rdg.ReturnPortfolioPartsModified("GetPartsAddedDeletedUpdatedInfo", PortfolioID, "PortfolioID");
                //if (PartsAddedDeleted)
                //    PopulatePortfolioPartsData();
            }

            EnblDsblBtnsOnYourPrtflioOwnrshpCntxt(PortfolioID);

            //if the user owns the selected portfolio, check if the portfolio contains the current part,
            //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
            bool blnCurrentPartFound = false;
            blnCurrentPartFound = isCurrentPartInPortfolio();
            if (blnCurrentPartFound)
                this.btnAddCurrentPart.Enabled = false;
            else
                this.btnAddCurrentPart.Enabled = true;

            if ((HFlag.Value != "PortfolioPartsAdded") && (HFlag.Value != "DeletePortfolio") && (HFlag.Value != "ExportPortfolio"))
                Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", jsMain, true);

            if (HFlag.Value == "Rename")
            {
                _PortfolioRenamed = txtRenamePortfolioName.Text;
                RenamePortfolio();
            }

            if (HFlag.Value == "Copy")
            {
                _PortfolioCopied = txtCopyPortfolioName.Text;
                CopyPortfolio();
            }
                
            btnPopupRename.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnPopupRename.UniqueID, "", "Rename", Session["UserLogin"].ToString(), chkIsPrivate.Checked.ToString());
            btnPopupCopy.OnClientClick = String.Format("fnClickOK('{0}','{1}','{2}','{3}','{4}')", btnPopupCopy.UniqueID, "", "Copy", Session["UserLogin"].ToString(), chkIsPrivate.Checked.ToString());

            if (HFlag.Value != "PortfolioPartsAdded")
                HFlag.Value = "";
            lblRenameErrorMessage1.Text = "";

            HighlightSelectedNode();

            if ((Session["Role"].ToString() != "Admin") && (Session["Role"].ToString() != "Bus Admin"))
                btnPrint.Attributes.Add("onclick", "javascript:CallPrintUsersGuest('print_grid','" + ddlPortfolios.SelectedItem.Text + "');");
            else
                btnPrint.Attributes.Add("onclick", "javascript:CallPrint('print_grid', 1,'" + ddlPortfolios.SelectedItem.Text + "');");

            
        }

        private bool isCurrentPartInPortfolio()
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            string PortfolioID = ddlPortfolios.SelectedValue.ToString();
            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");

            DataTable tbl = dsPartsForCurrentPortfolio.Tables[0];

            bool blnCurrentPartFound = false;
            if (dsPartsForCurrentPortfolio.Tables[0].Rows.Count > 0)
                blnCurrentPartFound = SearchPartInPortfolio(tbl, Session["CurrentPart"].ToString());

            if (blnCurrentPartFound)
                return true;
            else
                return false;
        }

     

        private void AddPortfoliosToDDL()
        {
            ddlPortfolios.Items.Clear();
            //ddlPortfolios.DataSource = dsPortfolios.Tables[PORTFOLIOS];
            //ddlPortfolios.DataTextField = dsPortfolios.Tables[PORTFOLIOS].Columns["PortfolioNm"].ToString();
            //ddlPortfolios.DataValueField = dsPortfolios.Tables[PORTFOLIOS].Columns["PortfolioID"].ToString();

            //ddlPortfolios.DataBind();


            foreach (DataRow dr in dsPortfolios.Tables[PORTFOLIOS].Rows)
            {
                ListItem li = new ListItem(dr["isPublic"].ToString() == "False" ? dr["PortfolioNm"].ToString() : dr["PortfolioNm"].ToString() + "[Public]", dr["PortfolioID"].ToString());

                switch (dr["isPublic"].ToString())
                {
                    case "False":
                        li.Attributes.Add("style", "background-color:white");
                        break;
                    case "True":
                        li.Attributes.Add("style", "background-color:yellow; font-weight:bold");
                        break;

                    default:
                        li.Attributes.Add("style", "background-color:fuchsia");
                        break;
                }
                ddlPortfolios.Items.Add(li);
            }
        }

        private void RetrieveSaveNFillGridWithCurrentPortfolio(bool Postback, bool isPublicNotMyPortfolio)
        {
            string PortfolioID = string.Empty;
            DataTable dt;
            
            DataSet dsCurrentPortfolio = null;
            ddlPortfolios.AutoPostBack = true;
            dsCurrentPortfolio = GetCurrentPortfolio(isPublicNotMyPortfolio);
            
            if (dsCurrentPortfolio.Tables[0].Rows.Count > 0)
            {
                _PortFolio = dsCurrentPortfolio.Tables[0].Rows[0].ItemArray[0].ToString();
                PortfolioID = dsCurrentPortfolio.Tables[0].Rows[0]["PortfolioID"].ToString();                
                chkIsPrivate.Checked = dsCurrentPortfolio.Tables[0].Rows[0]["isPublic"].ToString() == "False" ? true : false;
                _PortfolioIDCurrent = PortfolioID;

                txtRenamePortfolioName.Text = _PortFolio;

                if (!chkIsPrivate.Checked)
                {
                    lblPortfolioOwner.Visible = true;
                    lblPortfolioOwner.ForeColor = System.Drawing.Color.Green;
                    lblPortfolioOwner.Text = "Owner: " + dsCurrentPortfolio.Tables[0].Rows[0]["Login"].ToString();
                    if (Session["UserLogin"].ToString() != dsCurrentPortfolio.Tables[0].Rows[0]["Login"].ToString())
                    {
                        chkIsPrivate.Enabled = false;
                        btnDelete.Disabled = true;
                    }
                    else
                    {
                        chkIsPrivate.Enabled = true;
                        btnDelete.Disabled = false;
                    }
                }
                else
                {
                    lblPortfolioOwner.Visible = false;
                    chkIsPrivate.Enabled = true;
                }
            }

            if (!Postback)
            {
                SelectDropDownListWithData(this.ddlPortfolios, _PortFolio);
               
                //get the compatible parts info for the selected handheld
                RetrieveDataGateway rdg = new RetrieveDataGateway();
                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");
                if (dsPartsForCurrentPortfolio.Tables[0].Rows.Count > 0)
                {
                    dt = dsPartsForCurrentPortfolio.Tables[0];
                    GridViewPortfolio.DataSource = dt;
                    GridViewPortfolio.DataBind();
                }
            }
        }

        private DataSet GetCurrentPortfolio(bool isPublicNotMyPortfolio)
        {
            DataSet dsCurrentPortfolio = null;

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            if ((_PortFolio == null) || (_PortFolio == ""))
            {
                if ((Session["UserLogin"] != null) && (!isPublicNotMyPortfolio))
                {
                    dsCurrentPortfolio = rdg.GetDataInfoByOneParam("GetCurrentPortfolioForCurrentUser", Session["UserLogin"].ToString(), "UserLogin");
                }
                else if ((Session["UserLogin"] != null) && (isPublicNotMyPortfolio))
                {
                    //this means that the user has not created any
                    //portfolio and there may be public portfolios
                    //created by other users
                    string PortfolioNm = ddlPortfolios.SelectedItem.Text.ToString();
                    string PublicPortfolioID = ddlPortfolios.SelectedValue.ToString();
                    dsCurrentPortfolio = rdg.GetDataInfoByOneParam("GetSelectedPublicPortfolioInfo", PublicPortfolioID, "PortfolioID");
                    //if (PortfolioNm != "")
                    //{
                    //    dsPortfolios = (DataSet)Session["dsPortfolios"];
                    //    DataTable table = dsPortfolios.Tables[PORTFOLIOS];
                    //    string PublicPortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");
                        //dsCurrentPortfolio = rdg.GetDataInfoByOneParam("GetSelectedPublicPortfolioInfo", PublicPortfolioID, "PortfolioID");
                    //}

                }
                else
                    Response.Redirect(string.Format("~/Login.aspx"));
            }
            else if ((Session["UserLogin"] == null) && (isPublicNotMyPortfolio))
                Response.Redirect(string.Format("~/Login.aspx"));
            else if ((Session["UserLogin"] == null) && (!isPublicNotMyPortfolio))
                Response.Redirect(string.Format("~/Login.aspx"));

            return dsCurrentPortfolio;
        }

        private void SelectDropDownListWithData(DropDownList ddl, string dr)
        {
            ListItem lit = new ListItem();
            lit = (ListItem)ddl.Items.FindByText(dr);
            if (lit != null)
            {
                //Clear the previous selection
                ddl.SelectedIndex = -1;
                lit.Selected = true;
            }
        }

        private void EnableEditing()
        {
            if (Session["Role"] != null)
            {
                if ((Session["Role"].ToString().IndexOf("Admin") > -1) || (Session["Role"].ToString() == "Bus Admin"))
                    btnEdit.Visible = true;
            }
            else
                Response.Redirect(string.Format("~/Login.aspx"));
        }



        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ddlPortfolios.SelectedIndexChanged += new System.EventHandler(this.ddlPortfolios_SelectedIndexChanged);
        }

        private void ddlPortfolios_SelectedIndexChanged(object sender, System.EventArgs e)
        {   
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            string PortfolioID = ddlPortfolios.SelectedValue.ToString(); //SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");
            _PortfolioIDCurrent = PortfolioID;

            //Check if the user owns the portfolio he is viweing. If yes, then keep the related buttons enabled
            //If no, then make the related buttons disabled
            //EnblDsblBtnsOnYourPrtflioOwnrshpCntxt(PortfolioID);

            //Get the parts contained in the selected portfolio
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");

            //Populate the gridview with the parts contained in the selected portfolio
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            if ((Session["UserLogin"] != null) && (!isPublicPortfolioIDontOwn("ddlSelectedIndexChange")))
            {
                //pos = PortfolioNm.IndexOf("[Public]", 0);
                string strPortfolioNm = ReturnDDLSelectedItem();
                rdg.SaveCurrentPortfolioForCurrentUser("SaveCurrentPortfolioForCurrentUser", strPortfolioNm, Session["UserLogin"].ToString());
            }
            else if ((Session["UserLogin"] != null) && (isPublicPortfolioIDontOwn("ddlSelectedIndexChange")))
            {
                //do nothing
            }
            else if ((Session["UserLogin"] == null) && (isPublicPortfolioIDontOwn("ddlSelectedIndexChange")))
            {
                Response.Redirect(string.Format("~/Login.aspx"));
            }
            else if ((Session["UserLogin"] == null) && (!isPublicPortfolioIDontOwn("ddlSelectedIndexChange")))
            {
                Response.Redirect(string.Format("~/Login.aspx"));
            }

            RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("ddlSelectedIndexChange"));
            lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";
            
            
            
        }

        private void EnblDsblBtnsOnYourPrtflioOwnrshpCntxt(string PortfolioID)
        {
            string strStatus = string.Empty;
            string js = string.Empty;
            //Check if the user owns the portfolio he is viweing. If yes, then keep the related buttons enabled
            //If no, then make the related buttons disabled
            bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Style.Add("visibility", "hidden"); 

            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;    

                this.btnDelete.Style.Add("visibility", "visible");
                
                //if the user owns the selected portfolio, check if the portfolio contains the current part,
                //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
                if(dsPartsForCurrentPortfolio==null)
                {
                RetrieveDataGateway rdg = new RetrieveDataGateway();
                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");
                }

                DataTable table=dsPartsForCurrentPortfolio.Tables[0];

                bool blnCurrentPartFound=SearchPartInPortfolio(table, Session["CurrentPart"].ToString());
                if(blnCurrentPartFound)
                    this.btnAddCurrentPart.Enabled = false;
                else
                    this.btnAddCurrentPart.Enabled = true;
            }
        }

        private string ReturnDDLSelectedItem()
        {
            int pos = 0;
            string strPortfolioNm = string.Empty;
            pos = ddlPortfolios.SelectedItem.Text.IndexOf("[Public]", 0);
            strPortfolioNm = pos > 0 ? ddlPortfolios.SelectedItem.Text.Substring(0, pos) : ddlPortfolios.SelectedItem.Text;

            return strPortfolioNm;
        }

        private bool isPublicPortfolioIDontOwn(string Event)
        {
            bool blnisPublicPortfolioIDontOwn = false;
            string PublicPortfolioID = string.Empty;
            string PortfolioNm = string.Empty;
            DataSet dsPublicPortfolio = null;
            //DataTable table = null;

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            switch (Event)
            {
                case "Load":
                    if (Session["UserLogin"] != null)
                    {
                        DataSet dsCurrentPortfolio;
                        dsCurrentPortfolio = rdg.GetDataInfoByOneParam("GetCurrentPortfolioForCurrentUser", Session["UserLogin"].ToString(), "UserLogin");
                        if (dsCurrentPortfolio.Tables[0].Rows.Count > 0)
                        {
                            string PrivateCurrentPortfolioID = dsCurrentPortfolio.Tables[0].Rows[0]["PortfolioID"].ToString();
                            SelectDropDownListWithDataByValueSearch(this.ddlPortfolios, PrivateCurrentPortfolioID.ToString());
                            blnisPublicPortfolioIDontOwn = false;
                        }
                        else
                        {
                            PortfolioNm = ddlPortfolios.SelectedItem.Text.ToString();
                            PublicPortfolioID = ddlPortfolios.SelectedValue.ToString();
                            //dsPortfolios = (DataSet)Session["dsPortfolios"];
                            //table = dsPortfolios.Tables[PORTFOLIOS];
                            //PublicPortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");
                            dsPublicPortfolio = rdg.GetDataInfoByOneParam("GetSelectedPublicPortfolioInfo", PublicPortfolioID, "PortfolioID");
                            if ((dsPublicPortfolio.Tables[0].Rows.Count > 0) && (Session["UserLogin"].ToString() != dsPublicPortfolio.Tables[0].Rows[0]["Login"].ToString()))
                                blnisPublicPortfolioIDontOwn = true;
                        }
                    }
                    break;
                case "ddlSelectedIndexChange":
                    PortfolioNm = ddlPortfolios.SelectedItem.Text.ToString();
                    PublicPortfolioID = ddlPortfolios.SelectedValue.ToString();

                    //dsPortfolios = (DataSet)Session["dsPortfolios"];
                    //table = dsPortfolios.Tables[PORTFOLIOS];
                    //PublicPortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");
                    dsPublicPortfolio = rdg.GetDataInfoByOneParam("GetSelectedPublicPortfolioInfo", PublicPortfolioID, "PortfolioID");
                    if ((dsPublicPortfolio.Tables[0].Rows.Count > 0) && (Session["UserLogin"].ToString() != dsPublicPortfolio.Tables[0].Rows[0]["Login"].ToString()))
                        blnisPublicPortfolioIDontOwn = true;
                    break;
            }
                    
            
            return blnisPublicPortfolioIDontOwn;
        }

        private bool DoIOwnPortfolio()
        {
            bool blnDoIOwnPortfolio = false;
            string PortfolioID = string.Empty;
            string PortfolioNm = _PortfolioRenamed;
            DataSet dsPublicPortfolio = null;
            DataTable table = null;

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            if (Session["UserLogin"] != null)
            {
                dsPortfolios = (DataSet)Session["dsPortfolios"];
                table = dsPortfolios.Tables[PORTFOLIOS];
                PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

                dsPublicPortfolio = rdg.GetDataInfoByOneParam("GetSelectedPublicPortfolioInfo", PortfolioID, "PortfolioID");
                if ((dsPublicPortfolio.Tables[0].Rows.Count > 0) && (Session["UserLogin"].ToString() != dsPublicPortfolio.Tables[0].Rows[0]["Login"].ToString()))
                    blnDoIOwnPortfolio = true;
            }


            return blnDoIOwnPortfolio;
        }


        private int GetPortfolioCountFromDataTable(DataTable table, string PortfolioNm)
        {
            string expression;

            expression = "[" + table.Columns[0].ColumnName + "]" + " like " + "'%" + PortfolioNm + "%'";
            DataRow[] foundRows;
            
            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();
                dtvalid = table.Clone();

                foreach (DataRow dr in foundRows)
                {
                    if (dr[0].ToString() == PortfolioNm)
                    {
                        dtvalid.ImportRow(dr);
                    }
                    
                }

            }

            int ReturnedPortfolioCount = 0;

            if (dtvalid != null)
            {
                ReturnedPortfolioCount = dtvalid.Rows.Count;                
            }

            return ReturnedPortfolioCount;

        }

        private bool SearchPartInPortfolio(DataTable table, string PartNum)
        {
            string expression = "[" + table.Columns[2].ColumnName + "]" + " like " + "'%" + PartNum + "%'";
            DataRow[] foundRows;

            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            if (foundRows.Length > 0)
            {
                return true;
            }
            else
                return false;

        }

        private string SearchDropDownTextIDFromDataTable(DataTable table, string ddlSelectedText, string ColNm)
        {
            string expression;

            //int i = 0;

            int pos=ddlSelectedText.IndexOf("[Public]",0);
            string strdropDownSelectedValue = pos > 0 ? ddlSelectedText.Substring(0, pos) : ddlSelectedText;
            expression = "[" + table.Columns[0].ColumnName + "]" + " like " + "'%" + strdropDownSelectedValue + "%'";
            DataRow[] foundRows;
            
            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();
                dtvalid = table.Clone();

                foreach (DataRow dr in foundRows)
                {
                    if (dr[0].ToString() == strdropDownSelectedValue)
                    {
                        dtvalid.ImportRow(dr);
                    }
                    
                }

            }

            string ReturnedPortfolioID = string.Empty;

            if (dtvalid != null)
            {
                if ((pos > 0) && (foundRows.Length > 1))  //if the selected portfolio is public and the current
                                                          //user has a private portfolio with the same name
                {
                    if (dtvalid.Rows.Count == 2)//if the selected portfolio is public and the current
                                                //user has a private portfolio with the same name
                        foreach (DataRow dr in dtvalid.Rows)
                        {
                            
                            if (bool.Parse(dr["isPublic"].ToString()) == true)
                            {
                                ReturnedPortfolioID = dr[ColNm].ToString();
                            }
                            
                        }
                        
                    else if (dtvalid.Rows.Count == 1)//if the selected portfolio name is part of another prtfolio
                                                     //name, e.g portfolio names "9000" and "DoCoMo 9000"
                        ReturnedPortfolioID = dtvalid.Rows[0][ColNm].ToString();
                }
                else if ((pos > 0) && (foundRows.Length == 1))  //if the selected portfolio is public and the 
                                                                //current user has no private portfolio with the 
                                                                //same name
                    ReturnedPortfolioID = dtvalid.Rows[0][ColNm].ToString();
                else if ((pos <= 0) && (foundRows.Length == 1)) //if the selected portfolio is private and there is
                                                                //no public portfolio with the same name
                    if (dtvalid.Rows.Count > 0)
                    {
                        ReturnedPortfolioID = dtvalid.Rows[0][ColNm].ToString();
                        ReturnedPortfolioID = "";   //We will set the ReturnedPortfolioID to an empty string as 
                                                    //there is no public portfolio with the same name in this case
                    }
                    else
                        ReturnedPortfolioID = "";
                else if ((pos <= 0) && (foundRows.Length > 1)) //(1)if the selected portfolio is private and there is
                                                               //a public portfolio with the same name
                                                               //(2)if the selected portfolio is private and another
                                                               //user has a private portfolio with the same name
                                                               //the second scenario is out of scope as the main
                                                               //only returns portfolio for the current user as
                                                               //as public portfolios if any
                {
                    if (dtvalid.Rows.Count == 2)
                        foreach (DataRow dr in dtvalid.Rows)
                        {

                            if (bool.Parse(dr["isPublic"].ToString()) == false)
                            {
                                ReturnedPortfolioID = dr[ColNm].ToString();
                            }

                        }
                    else if (dtvalid.Rows.Count == 1)//if the selected portfolio is private and there is
                                                     //no public portfolio with the same name
                    {
                        ReturnedPortfolioID = dtvalid.Rows[0][ColNm].ToString();
                        ReturnedPortfolioID = "";   //We will set the ReturnedPortfolioID to an empty string as 
                                                    //there is no public portfolio with the same name in this case
                    }
                    else if (dtvalid.Rows.Count == 0)
                        ReturnedPortfolioID = "";
                }
                    
            }
            else
                ReturnedPortfolioID= "";

            return ReturnedPortfolioID;

        }


        private bool SearchDropDownPortfolioPrivacyFromDataTable(DataTable table, string PortfolioNm, string ColNm, string Event, string CheckType)
        {
            string expression;

            int pos = PortfolioNm.IndexOf("[Public]", 0);
            string strPortfolioNm = pos > 0 ? PortfolioNm.Substring(0, pos) : PortfolioNm;

            expression = "[" + table.Columns[0].ColumnName + "]" + " like " + "'%" + strPortfolioNm + "%'";
            DataRow[] foundRows;
            
            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();
                dtvalid = table.Clone();

                foreach (DataRow dr in foundRows)
                {
                    if (dr[0].ToString() == strPortfolioNm)
                        dtvalid.ImportRow(dr);
                }

            }

            bool isPublic = false;

            if(Event=="Create")
                isPublic=bool.Parse(dtvalid.Rows[0][ColNm].ToString());
            else if (Event == "CheckedChanged")
            {
                if (dtvalid.Rows.Count == 2)//if the selected portfolio is private and there
                                            //is no other public portfolio with the same name
                    isPublic = bool.Parse(dtvalid.Rows[1][ColNm].ToString());
                else if (dtvalid.Rows.Count == 1)//if the selected portfolio is private and a second
                                                 //user has a public portfolio with the same name
                    isPublic = bool.Parse(dtvalid.Rows[0][ColNm].ToString());
            }
            else if (Event == "Rename")
            {
                if (CheckType == "isPublic")
                {
                    if (dtvalid.Rows.Count == 2)//if the renamed portfolio is private and there
                    //is no other public portfolio with the same name
                    {
                        foreach (DataRow dr in dtvalid.Rows)
                        {

                            if (bool.Parse(dr["isPublic"].ToString()) == true)
                            {
                                isPublic = bool.Parse(dr[ColNm].ToString());
                                //isPublic = bool.Parse(dtvalid.Rows[1][ColNm].ToString());
                            }

                        }
                    }
                    else if (dtvalid.Rows.Count == 1)//if the selected portfolio is private and a second
                        //user has a public portfolio with the same name
                        isPublic = bool.Parse(dtvalid.Rows[0][ColNm].ToString());
                }
                else if (CheckType == "isPrivate")
                {
                    if (dtvalid.Rows.Count == 2)//if the renamed portfolio is private and there
                    //is no other public portfolio with the same name
                    {
                        foreach (DataRow dr in dtvalid.Rows)
                        {

                            if (bool.Parse(dr["isPublic"].ToString()) == false)
                            {
                                isPublic = bool.Parse(dr[ColNm].ToString());
                                //isPublic = bool.Parse(dtvalid.Rows[1][ColNm].ToString());
                            }

                        }
                    }
                    else if (dtvalid.Rows.Count == 1)//if the selected portfolio is private and a second
                        //user has a public portfolio with the same name
                        isPublic = bool.Parse(dtvalid.Rows[0][ColNm].ToString());
                }
            }

            return isPublic;

        }

        private bool SearchDropDownPortfolioOwnerFromDataTable(DataTable table, string PortfolioNm, string ColNm)
        {
            string expression=string.Empty;
            string strPortfolioNm = string.Empty;
            int pos = 0;
            if (ColNm == "PortfolioNm")
            {
                pos = PortfolioNm.IndexOf("[Public]", 0);
                strPortfolioNm = pos > 0 ? PortfolioNm.Substring(0, pos) : PortfolioNm;
                expression = "[" + table.Columns[0].ColumnName + "]" + " like " + "'%" + strPortfolioNm + "%'";
            }
            else if (ColNm == "PortfolioID")
                expression = "[" + table.Columns[1].ColumnName + "]=" + PortfolioNm + "";

            DataRow[] foundRows;

            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();
                dtvalid = table.Clone();

                foreach (DataRow dr in foundRows)
                {
                    if (ColNm == "PortfolioNm")
                    {
                        if (dr[0].ToString() == strPortfolioNm)
                            dtvalid.ImportRow(dr);
                    }
                    else if (ColNm == "PortfolioID")
                    {
                        if (dr[1].ToString() == PortfolioNm)
                            dtvalid.ImportRow(dr);
                    }
                }
            }

            string sLogin = string.Empty;
            bool IOwnIt = false;

            if (dtvalid != null)
            {
                foreach (DataRow dr in dtvalid.Rows)
                {
                    sLogin = dr["Login"].ToString();
                    if (sLogin == Session["UserLogin"].ToString())
                        IOwnIt= true;
                    else
                        IOwnIt= false;
                }
                    
            }

            return IOwnIt;

        }

        protected void GridViewPortfolio_Init(object sender, EventArgs e)
        {
            AddGridViewColumns();
        }

        protected void GridViewPortfolio_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridViewPortfolio.PageIndex = e.NewPageIndex;
        }

        protected void GridViewPortfolio_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // Locate column with hyperlink object
            foreach (TableCell tc in e.Row.Cells)
            {
                tc.Attributes["style"] = "border-color:#344F3E";
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Check if the user owns the portfolio he is viweing. If yes, then keep the related buttons enabled
                //If no, then make the related buttons disabled
                if (_IsMyPortFolio)
                    e.Row.Attributes.Add("onclick", "rowSelected('" + ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[1].ToString() + "',  '" + ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[2].ToString() + "'); javascript:ChangeRowColor('" + e.Row.ClientID + "')");
            }
        }

        protected void GridViewPortfolio_SelectedIndexChanged(Object sender, EventArgs e)
        {
            GridViewPortfolio.SelectedRowStyle.BackColor = System.Drawing.Color.FromName("#344F3E");
            GridViewPortfolio.SelectedRowStyle.ForeColor = System.Drawing.Color.Yellow; 
        }

        public void GridViewPortfolio_RowEditing(object sender, GridViewEditEventArgs e)
        {

        }

        protected void GridViewPortfolio_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void GridViewPortfolio_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }



        public void GridViewPortfolio_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridViewPortfolio.EditIndex = -1;
        }

        public void GridViewPortfolio_RowUpdating(Object sender, GridViewUpdateEventArgs e)
        {

        }

        private void DeselectAllItemsForTheListBox(ListBox lst)
        {
            foreach (ListItem item in lst.Items)
            {
                if (item.Selected)
                {
                    item.Selected = false;
                }
            }

        }

        private void RetrieveData(bool reloadFromDB)
        {
            //we retrive data only if its not in the session.
            if (Session["dsPortfolios"] == null || reloadFromDB)
            {
                //load the dataset from the database for the refreshed data
                LoadData();
                
            }
        }

        private void LoadData()
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            if (Session["UserLogin"] != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(Session["UserLogin"].ToString());
                sb.Append("|");
                sb.Append(_PartNumber);
                dsPortfolios = rdg.GetPortfoliosForCurrentUser("GetAllPortfoliosForCurrentUser", sb.ToString(), "UserLoginAndPartNum");

                dsPortfolios.Tables[0].TableName = PORTFOLIOS;
                dsPortfolios.Tables[1].TableName = ACCESSORIES;
                dsPortfolios.Tables[2].TableName = COMPATIBILITY;

                Session["dsPortfolios"] = dsPortfolios as DataSet;
            }
        }

        
        private void LoadHeaderControls(string EditMode)
        {
            try
            {
                RetrieveDataGateway rdg = new RetrieveDataGateway();

                if (dsPortfolios == null)
                    dsPortfolios = (DataSet)Session["dsPortfolios"];

                
                PartNumberEditReadOnlyPanel.Visible = true;
                if (dsPortfolios.Tables[ACCESSORIES].Rows.Count > 0)
                {
                    //lblPartNumInfoHeader.Text = rdg.GetParameterString(dsPortfolios.Tables[ACCESSORIES].Rows[0]["AccPartNum"].ToString());
                    //lblPartDescInfoHeader.Text = rdg.GetParameterString(dsPortfolios.Tables[ACCESSORIES].Rows[0]["SecDesc"].ToString() == "" ? dsPortfolios.Tables[ACCESSORIES].Rows[0]["SAPDesc"].ToString() : dsPortfolios.Tables[ACCESSORIES].Rows[0]["SecDesc"].ToString());
                }
            }
            catch (SqlException err)
            {
                string error = err.Number.ToString();
                Response.Redirect(string.Format("~/Login.aspx"));
            }
            
        }

        private void LoadPanelControl(string EditMode, string PanelName)
        {
            if (dsPortfolios == null)
                dsPortfolios = (DataSet)Session["dsPortfolios"];

            switch (PanelName)
            {
                case "ReadOnlyPanel":
                    StringBuilder sb = new StringBuilder();
                    
                    break;

                case "EditPanel":
                    if (EditMode == "Edit")
                    {
                        StringBuilder sbEdit = new StringBuilder();
                    }

                    break;
                case "DescReadOnlyPanel":                   
                    LoadHeaderControls("ReadOnly");                  
                    break;
                case "DescEditPanel":
                    if (EditMode == "Edit")
                    {
                        LoadHeaderControls("Edit");
                    }
                    else if (EditMode == "Add")
                    {
                        LoadHeaderControls("Add");
                    }
                    break;
                case "PackagingEditPanel":
                    LoadHeaderControls("Edit");

                    RetrieveDataGateway rdg = new RetrieveDataGateway();
                    break;
                case "PackagingReadOnlyPanel":
                    LoadHeaderControls("Edit");

                    rdg = new RetrieveDataGateway();

                    if (dsPortfolios.Tables[ACCESSORIES].Rows.Count > 0)
                    {
                       
                    }

                    break;                    
            }            
        }
        
        private void LoadTreeView()
        {
            switch (_CalledFrom)
            {
                case "ProjMgmt":
                    MiscHelpers.LoadTreeView(Server.MapPath("Treeviewnodes2.xml"), "ProjMngTab.aspx", this.leftNavTreeView);
                    break;
                case "admin":
                    MiscHelpers.LoadTreeView(Server.MapPath("Treeviewnodes2.xml"), "admin.aspx", this.leftNavTreeView);
                    break;
            }
        
        }

        private void HighlightSelectedNode()
        {
            // Iterate through the child nodes of the root node "Accessories Central" and find
            // the node for "Basic Product Info".
            switch (_CalledFrom)
            {

                case "ProjMgmt":
                    foreach (TreeNode node in leftNavTreeView.FindNode("Project Mgmt").ChildNodes)
                    {
                        switch (node.Text)
                        {
                            case "Portfolios":
                                // Select the node using the Selected property.
                                node.Selected = true;
                                node.ToolTip = "Portfolios";
                                break;

                            default:
                                // Do nothing.
                                break;
                        }
                    }
                    break;
                case "admin":
                    foreach (TreeNode node in leftNavTreeView.FindNode("Project Mgmt").ChildNodes)
                    {
                        switch (node.Text)
                        {
                            case "Portfolios":
                                // Select the node using the Selected property.
                                node.Selected = true;
                                node.ToolTip = "Portfolios";
                                break;

                            default:
                                // Do nothing.
                                break;
                        }
                    }
                    break;
            }
        }

        private void GetMaterialGroupsHierarchy()
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            dsMaterialHierarchy = rdg.GetDataInfoWithoutParam("GetMaterialGroupsHierarchyInfo");

            dsMaterialHierarchy.Tables[0].TableName = CLANS;
            dsMaterialHierarchy.Tables[1].TableName = FAMILIES;
            dsMaterialHierarchy.Tables[2].TableName = MG;
            dsMaterialHierarchy.Tables[3].TableName = HIERARCHY;
            dsMaterialHierarchy.Tables[4].TableName = COMPATIBILITYCOLUMNS;
            dsMaterialHierarchy.Tables[5].TableName = COMPATIBILITYHANDHELDCOLUMNS;

            Session["dsMaterialHierarchy"] = dsMaterialHierarchy as DataSet;
        }

        protected void btnPopupCopy_Click(object sender, EventArgs e)
        {

        }
        



        protected void btnPopupRename_Click(object sender, EventArgs e)
        {
            //_PortfolioRenamed = this.txtRenamePortfolioName.Text;

            //Note that the portfolio can only be renamed by the user who owns it (whether private or public). 
            //The rename button will be disabled if the user is viwing a public portfolio owned by another user.

            ////First check if there exists a portfolio the user is renaming to
            //int iPortfolioRenamedExistCount = PortfolioRenamedExistCount(_PortfolioRenamed);
            //bool isCurrentPortfolioPublic = false;
            //bool blnDoIOwn = false;

            //switch (iPortfolioRenamedExistCount)
            //{
            //    case 0:
            //        //Do nothing and move forward to rename
            //        break;
            //    case 1: //if the portfolio name the user is renaming to is already in use (private owned by this
            //            //user or public owned by this user or a different user)
            //        //(1) Check the current portfolio being renamed is private or public
            //        isCurrentPortfolioPublic = this.chkIsPrivate.Checked == false ? true : false;

            //        //(2) Check the portfolio it is renamed to is private or public
            //        _isPublicPortfolio = CheckIfRenamedPortfolioIsPublic("Rename");

            //        //if the current portfolio being renamed is public and the portfolio for the portfolio name 
            //        //in use (the user is trying to rename to) is also public, then you can not move forward to
            //        //rename, display the error and return
            //        if ((isCurrentPortfolioPublic) && (_isPublicPortfolio))
            //        {
            //            DisplayPortfolioRenameErrorMessage();
            //            return;
            //        }
            //        //if the current portfolio being renamed is private and the portfolio for the portfolio name 
            //        //in use (the user is trying to rename to) is also private owned by the user, then you can not 
            //        //move forward to rename, display the error and return
            //        else if ((!isCurrentPortfolioPublic) && (!_isPublicPortfolio))
            //        {
            //            DisplayPortfolioRenameErrorMessage();
            //            return;
            //        }
            //        //if the current portfolio being renamed is private and the portfolio for the portfolio name 
            //        //in use (the user is trying to rename to) is public, then there are two cases
            //        //(1) If the portfolio for the portfolio name in use (the user is trying to rename to) is 
            //        //public owned by the current user, then you can not move forward to rename, display the 
            //        //error and return
            //        //(2) If the portfolio for the portfolio name in use (the user is trying to rename to) is 
            //        //public owned by another user, then you can move forward to rename this as a private 
            //        //portfolio
            //        else if ((!isCurrentPortfolioPublic) && (_isPublicPortfolio))
            //        {
            //            blnDoIOwn = DoIOwnPortfolio();
            //            if (blnDoIOwn)
            //            {
            //                DisplayPortfolioRenameErrorMessage();
            //                return;
            //            }
            //            else                        
            //            {
            //                //do nothing
            //            }

            //        }
            //        //if the current portfolio being renamed is public and the portfolio for the portfolio name 
            //        //in use (the user is trying to rename to) is private, then you can not move forward to rename, 
            //        //display the error and return
            //        else if ((isCurrentPortfolioPublic) && (!_isPublicPortfolio))
            //        {
            //            DisplayPortfolioRenameErrorMessage();
            //            return;
            //        }

            //        break;
            //    case 2://if the portfolio name the user is renaming to is already in use (private owned by this
            //        //user as well as public owned by a different user). In this case the user can not move 
            //        //forward to rename, display the error and return
            //        DisplayPortfolioRenameErrorMessage();
            //        return;
            //        //break;                   
                   
            //}

            //////string ToBeRenamedPortfolioNm = ReturnDDLSelectedItem();

            //////dsPortfolios = (DataSet)Session["dsPortfolios"];
            //////DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            //////string ToBeRenamedPortfolioID = SearchDropDownTextIDFromDataTable(table, ToBeRenamedPortfolioNm, "PortfolioID");

            //////RetrieveDataGateway rdg = new RetrieveDataGateway();
            //////rdg.RenamePortfolioForCurrentUser("RenamePortfolioForCurrentUser", ToBeRenamedPortfolioID, _PortfolioRenamed, Session["UserLogin"].ToString());


            //////RetrieveData(true);

            //////AddPortfoliosToDDL();
            //////_PortFolio = "";
            //////RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));

            ////////Get the parts contained in the selected portfolio
            //////dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", ToBeRenamedPortfolioID, "PortfolioID");

            ////////Populate the gridview with the parts contained in the selected portfolio
            //////DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            //////GridViewPortfolio.DataSource = dt;
            //////GridViewPortfolio.DataBind();

            //First check if the portfolio the user renaming to is private or public
             //_isPublicPortfolio = CheckIfRenamedPortfolioIsPublic("Rename");
             //_isPrivatePortfolio = CheckIfRenamedPortfolioIsPrivate("Rename");
             //_isPrivatePortfolio = _isPrivatePortfolio == false ? true : false;

             

            //Case when you are trying to rename this portfolio to a name that both exists as a public 
            //portfolio (owned by another user) as well as a private portfolio owned by you
            //if ((_isPublicPortfolio) && (_isPrivatePortfolio) && (iPortfolioRenamedExistCount==2))

            
            //Update the Renamed portfolio to the database

            //RetrieveDataGateway rdg = new RetrieveDataGateway();
            //bool isPublic = this.chkIsPrivate.Checked == false ? true : false;
            //rdg.UpdatePrivacyFlagForSelectedPortfolio("UpdatePrivacyFlagForSelectedPortfolio", _PortfolioIDCurrent, isPublic);
            //if (!chkIsPrivate.Checked)
            //{
            //    lblPortfolioOwner.Visible = true;
            //    if (Session["UserLogin"] != null)
            //    {
            //        lblPortfolioOwner.ForeColor = System.Drawing.Color.Green;
            //        lblPortfolioOwner.Text = "Owner: " + Session["UserLogin"].ToString();
            //    }
            //    else
            //        Response.Redirect(string.Format("~/Login.aspx"));
            //}
            //else
            //    lblPortfolioOwner.Visible = false;

        }

        private void RenamePortfolio()
        {
            string ToBeRenamedPortfolioNm = ReturnDDLSelectedItem();
            string ToBeRenamedPortfolioID = ddlPortfolios.SelectedValue.ToString();

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            //string ToBeRenamedPortfolioID = SearchDropDownTextIDFromDataTable(table, ToBeRenamedPortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            rdg.RenamePortfolioForCurrentUser("RenamePortfolioForCurrentUser", ToBeRenamedPortfolioID, _PortfolioRenamed, Session["UserLogin"].ToString());


            RetrieveData(true);

            AddPortfoliosToDDL();
            _PortFolio = "";
            RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));

            //Get the parts contained in the selected portfolio
            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", ToBeRenamedPortfolioID, "PortfolioID");

            //Populate the gridview with the parts contained in the selected portfolio
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();
        }

        private void CopyPortfolio()
        {
            string ToBeCopiedPortfolioNm = ReturnDDLSelectedItem();
            string ToBeCopiedPortfolioID = ddlPortfolios.SelectedValue.ToString();

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            //string ToBeCopiedPortfolioID = SearchDropDownTextIDFromDataTable(table, ToBeCopiedPortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            //Copy a new portfolio by calling the stored proc CopyPortfolioForCurrentUser and retrieve the newly 
            //inserted portfolioID as output parameter 
            int PortfolioID = rdg.CopyPortfolioForCurrentUser("CopyPortfolioForCurrentUser", ToBeCopiedPortfolioID, _PortfolioCopied, Session["UserLogin"].ToString());

            RetrieveData(true);

            AddPortfoliosToDDL();
            _PortFolio = "";
            RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));

            //Get the parts contained in the selected portfolio
            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");

            //Populate the gridview with the parts contained in the selected portfolio
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();
        }


        private void DisplayPortfolioRenameErrorMessage()
        {
            this.Rename_ModalPopupExtender.Show();
            lblRenameErrorMessage1.Visible = true;
            lblRenameErrorMessage1.ForeColor = System.Drawing.Color.Red;
            lblRenameErrorMessage1.Text = "This portfolio name is already in use...";
        }

        protected void btnRenameCancel_Click(object sender, EventArgs e)
        {
            string s = string.Empty;
            s = "great";
        }

        protected void btnAddPartToPortfolioAdd_Click(object sender, EventArgs e)
        {

        }

        protected void btnRename_Click(object sender, EventArgs e)
        {

        }

        protected void btnAddPart_Click(object sender, EventArgs e)
        {

        }

        protected void btnAddCurrentPart_Click(object sender, EventArgs e)
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            string PortfolioID = ddlPortfolios.SelectedValue.ToString();
            DataSet dsPartID = rdg.GetIDByPartNumber("GetIDByPart", Session["CurrentPart"].ToString(), "PartNumber");
            int iAccID = int.Parse(dsPartID.Tables[0].Rows[0]["AccID"].ToString());

            rdg.UpdatePortfolioInfo("UpdatePortfolioPartInfo", int.Parse(PortfolioID.ToString()), iAccID);

            RetrieveData(true);

            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";

            //if the user owns the selected portfolio, check if the portfolio contains the current part,
            //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
            bool blnCurrentPartFound = false;
            blnCurrentPartFound = isCurrentPartInPortfolio();
            if (blnCurrentPartFound)
                this.btnAddCurrentPart.Enabled = false;
            else
                this.btnAddCurrentPart.Enabled = true;

            //string js = string.Empty;
            //js = js + "TriggerAjaxCall()";
            //jsMain = jsMain + js;
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", jsMain, true);

            //HFlag.Value = "";
        }

        protected void btnDeletePart_Click(object sender, EventArgs e)
        {
            ////  get the gridviewrow from the sender so we can get the datakey we need
            //Button btnDelete = sender as Button;
            //GridViewRow row = (GridViewRow)btnDelete.NamingContainer;
            ////  find the item and remove it
            //ToDo itemToRemove = this.ToDoList[row.RowIndex];
            //this.ToDoList.Remove(itemToRemove);
            //  rebind the datasource
            lblConfirmMessage.Text = HDeleteWarningMessage.Value;
            //lblConfirmMessage.Text = HDeleteWarningMessage.Value;
            string DeleteRowID = HPartIDForGridviewRow.Value;
            //this.gvToDoList.DataSource = this.ToDoList;
            //this.gvToDoList.DataBind();

            
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnOKDeletePortfolio_Click(object sender, EventArgs e)
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            string PortfolioID = ddlPortfolios.SelectedValue.ToString();

            rdg.DeletePortfolio("DeletePortfolio", int.Parse(PortfolioID), Session["UserLogin"].ToString());
            RetrieveData(true);

            if (dsPortfolios.Tables[PORTFOLIOS].Rows.Count > 0)
            {
                //btnEdit.Enabled = true;
                AddPortfoliosToDDL();

                RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));

                PortfolioID = ddlPortfolios.SelectedValue.ToString();
                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");
                if (dsPartsForCurrentPortfolio.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
                    GridViewPortfolio.DataSource = dt;
                    GridViewPortfolio.DataBind();

                    lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";
                }
            }

            HFlag.Value = "";
        }

        

        protected void btnOK_Click(object sender, EventArgs e)
        {
            //DataTable table;
            DataTable dt;
            string PortfolioID = string.Empty;
            string DeleteRowAccID = HPartIDForGridviewRow.Value;
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            if (DeleteRowAccID == "")
            {
                lblErrorMessageMain.Text = "Please select the part you want to delete!";
                lblErrorMessageMain.Visible = true;

                PortfolioID = ddlPortfolios.SelectedValue.ToString();

                //table = dsPortfolios.Tables[PORTFOLIOS];
                //PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
                dt = dsPartsForCurrentPortfolio.Tables[0];
                GridViewPortfolio.DataSource = dt;
                GridViewPortfolio.DataBind();
                return;
            }

            txtRenamePortfolioName.Text = PortfolioNm;

            PortfolioID = ddlPortfolios.SelectedValue.ToString();

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //table = dsPortfolios.Tables[PORTFOLIOS];
            //PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            rdg.DeletePartFromPortfolio("DeletePartFromPortfolio", int.Parse(DeleteRowAccID), int.Parse(PortfolioID));
            RetrieveData(true);

            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
            dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            //Check if the user owns the portfolio he is viweing. If yes, then keep the related buttons enabled
            //If no, then make the related buttons disabled
            //EnblDsblBtnsOnYourPrtflioOwnrshpCntxt(PortfolioID);

            lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";
            HPartIDForGridviewRow.Value = "";

            //Check if the PartsAddedDeletedUpdated flag is set to true in the db for the portfolio changed
            //This will allow the front app to decide whether reload the data from the db or not
            //if the flag is true then data should be reloaded, otherwise not
            bool PartsAddedDeleted = rdg.ReturnPortfolioPartsModified("GetPartsAddedDeletedUpdatedInfo", PortfolioID, "PortfolioID");
            //if (PartsAddedDeleted)
            //{
            //    PopulatePortfolioPartsData();
            //    rdg.ResetPartsAddedDeletedUpdatedInfo("ResetPartsAddedDeletedUpdatedInfo", int.Parse(PortfolioID));
            //}

            //if the user owns the selected portfolio, check if the portfolio contains the current part,
            //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
            bool blnCurrentPartFound = false;
            blnCurrentPartFound = isCurrentPartInPortfolio();
            if (blnCurrentPartFound)
                this.btnAddCurrentPart.Enabled = false;
            else
                this.btnAddCurrentPart.Enabled = true;
        }
        

        protected void btnCompAdd_Click(object sender, EventArgs e)
        {
            if (optHHCompat.Selected)
                CreateHandheldBasedPortfolio();
            else
                CreateEmptyPortfolio();

            //if the user owns the selected portfolio, check if the portfolio contains the current part,
            //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
            bool blnCurrentPartFound = false;
            blnCurrentPartFound = isCurrentPartInPortfolio();
            if (blnCurrentPartFound)
                this.btnAddCurrentPart.Enabled = false;
            else
                this.btnAddCurrentPart.Enabled = true;
   
        }

        private void CreateHandheldBasedPortfolio()
        {
            DataTable dt;
          
            string HandheldID = HSelectedListBoxItem.Value;
            if (HandheldID=="")
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Please select a handheld from the listbox and then proceed";
                CompatPanel_ModalPopupExtender.Show();
                return;
            }

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            _PortFolio = txtPortfolioName.Text;

            bool blnDoesPortfolioExist = DoesPortfolioExist();

            bool blnIsMyPortFolio = CheckIfIOwnPortfolio();

            if (blnDoesPortfolioExist)
                _isPublicPortfolio = CheckIfPortfolioIsPublic("Create");

            //The current user is not allowed to create a new portfolio if he has already created another portfolio 
            //(whether private or public) with the same name (i.e. if the portfolio already exists with the same 
            //name for the same user, show the message: "This portfolio name is already in use")
            if ((blnDoesPortfolioExist) && (blnIsMyPortFolio))
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "This portfolio name is already in use";
                CompatPanel_ModalPopupExtender.Show();
                return;
            }
            else if ((blnDoesPortfolioExist) && (_isPublicPortfolio) && (!blnIsMyPortFolio))
                //The current user is allowed to create a private portfolio with the same name as is already 
                //created by another user
                _isPublicPortfolio = false;


            //Add a new portfolio by calling the stored proc AddNewPortfolio and retrieve the newly inserted
            //portfolioID as output parameter 
            int PortfolioID = rdg.GetPortfolioID("AddNewPortfolio", _PortFolio);

            chkIsPrivate.Checked = true;
            chkIsPrivate.Enabled = true;
            lblPortfolioOwner.Visible = false;

            //get the compatible parts info for the selected handheld
            DataSet dsPartsForSelectedHandheld = rdg.GetDataInfoByOneParam("GetPartsForGivenHandheld", HandheldID, "HandheldID");

            if (dsPartsForSelectedHandheld.Tables[0].Rows.Count > 0)
            {
                //dt = dsPartsForSelectedHandheld.Tables[0];
                //GridViewPortfolio.DataSource = dt;
                //GridViewPortfolio.DataBind();

                if (Session["UserLogin"] != null)
                {
                    rdg.UpdatePortfolioUserInfo("UpdatePortfolioUserInfo", Session["UserLogin"].ToString(), PortfolioID);
                    rdg.SaveCurrentPortfolioForCurrentUser("SaveCurrentPortfolioForCurrentUser", _PortFolio, Session["UserLogin"].ToString());
                }
                else
                    Response.Redirect(string.Format("~/Login.aspx"));

                foreach (DataRow dr in dsPartsForSelectedHandheld.Tables[0].Rows)
                {
                    rdg.UpdateCompatibilityInfo("UpdatePortfolioInfo", int.Parse(dr["AccID"].ToString()), PortfolioID);
                }

                RetrieveData(true);
                AddPortfoliosToDDL();

                SelectDropDownListWithDataByValueSearch(this.ddlPortfolios, PortfolioID.ToString());

                DataSet dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
                dt = dsPartsForCurrentPortfolio.Tables[0];
                GridViewPortfolio.DataSource = dt;
                GridViewPortfolio.DataBind();

                txtPortfolioName.Text = "";
                HSelectedListBoxItem.Value = "";

                lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";
            }

        }

         private void CreateEmptyPortfolio()
         {
            DataTable dt;
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            _PortFolio = txtPortfolioName.Text;

            bool blnDoesPortfolioExist = DoesPortfolioExist();

            bool blnIsMyPortFolio = CheckIfIOwnPortfolio();

            if (blnDoesPortfolioExist)
                _isPublicPortfolio = CheckIfPortfolioIsPublic("Create");

            //The current user is not allowed to create a new portfolio if he has already created another portfolio 
            //(whether private or public) with the same name (i.e. if the portfolio already exists with the same 
            //name for the same user, show the message: "This portfolio name is already in use")
            if ((blnDoesPortfolioExist) && (blnIsMyPortFolio))
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "This portfolio name is already in use";
                CompatPanel_ModalPopupExtender.Show();
                return;
            }
            else if ((blnDoesPortfolioExist) && (_isPublicPortfolio) && (!blnIsMyPortFolio))
                //The current user is allowed to create a private portfolio with the same name as is already 
                //created by another user
                _isPublicPortfolio = false;


            //Add a new portfolio by calling the stored proc AddNewPortfolio and retrieve the newly inserted
            //portfolioID as output parameter 
            int PortfolioID = rdg.GetPortfolioID("AddNewPortfolio", _PortFolio);

            chkIsPrivate.Checked = true;
            chkIsPrivate.Enabled = true;
            lblPortfolioOwner.Visible = false;

            if (Session["UserLogin"] != null)
            {
                rdg.UpdatePortfolioUserInfo("UpdatePortfolioUserInfo", Session["UserLogin"].ToString(), PortfolioID);
                rdg.SaveCurrentPortfolioForCurrentUser("SaveCurrentPortfolioForCurrentUser", _PortFolio, Session["UserLogin"].ToString());
            }
            else
                Response.Redirect(string.Format("~/Login.aspx"));


            RetrieveData(true);
            AddPortfoliosToDDL();

            SelectDropDownListWithDataByValueSearch(this.ddlPortfolios, PortfolioID.ToString());

            DataSet dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
            dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            txtPortfolioName.Text = "";
            HSelectedListBoxItem.Value = "";

            lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";


        }

         private bool DoesPortfolioExist()
         {
             dsPortfolios = (DataSet)Session["dsPortfolios"];
             DataTable table = dsPortfolios.Tables[PORTFOLIOS];
             string PortfolioID = SearchDropDownTextIDFromDataTable(table, _PortFolio, "PortfolioID");

             if (PortfolioID != "")
                 return true;
             else
                 return false;
         }

         private int PortfolioRenamedExistCount(string PortFolio)
         {
             dsPortfolios = (DataSet)Session["dsPortfolios"];
             DataTable table = dsPortfolios.Tables[PORTFOLIOS];
             int PortfolioCount = GetPortfolioCountFromDataTable(table, PortFolio);

             return PortfolioCount;
         }

         private bool CheckIfPortfolioIsPublic(string Event)
         {
             if (dsPortfolios == null)
                 dsPortfolios = (DataSet)Session["dsPortfolios"];

             DataTable table = dsPortfolios.Tables[PORTFOLIOS];

             bool isPortfolioPublic = SearchDropDownPortfolioPrivacyFromDataTable(table, _PortFolio, "isPublic", Event, "isPublic");

             return isPortfolioPublic;

         }

         private bool CheckIfRenamedPortfolioIsPublic(string Event)
         {
             if (dsPortfolios == null)
                 dsPortfolios = (DataSet)Session["dsPortfolios"];

             DataTable table = dsPortfolios.Tables[PORTFOLIOS];

             bool isPortfolioPublic = SearchDropDownPortfolioPrivacyFromDataTable(table, _PortfolioRenamed, "isPublic", Event, "isPublic");

             return isPortfolioPublic;

         }

         private bool CheckIfRenamedPortfolioIsPrivate(string Event)
         {
             if (dsPortfolios == null)
                 dsPortfolios = (DataSet)Session["dsPortfolios"];

             DataTable table = dsPortfolios.Tables[PORTFOLIOS];

             bool isPortfolioPrivate = SearchDropDownPortfolioPrivacyFromDataTable(table, _PortfolioRenamed, "isPublic", Event, "isPrivate");

             return isPortfolioPrivate;

         }

         private bool CheckIfIOwnPortfolio()
         {
             if (dsPortfolios == null)
                 dsPortfolios = (DataSet)Session["dsPortfolios"];

             DataTable table = dsPortfolios.Tables[PORTFOLIOS];

             if (_PortFolio == "")
                 _PortFolio = ddlPortfolios.SelectedItem.Text;

             bool isMyPortfolio = SearchDropDownPortfolioOwnerFromDataTable(table, _PortFolio, "PortfolioNm");

             return isMyPortfolio;

         }

         private bool CheckIfIOwnPortfolio(string PortfolioID)
         {
             if (dsPortfolios == null)
                 dsPortfolios = (DataSet)Session["dsPortfolios"];

             DataTable table = dsPortfolios.Tables[PORTFOLIOS];

             //if (_PortFolio == "")
             //    _PortFolio = ddlPortfolios.SelectedItem.Text;

             bool isMyPortfolio = SearchDropDownPortfolioOwnerFromDataTable(table, PortfolioID, "PortfolioID");

             _IsMyPortFolio = isMyPortfolio;

             return isMyPortfolio;

         }


      

        private void SelectDropDownListWithDataByValueSearch(DropDownList ddl, string ID)
        {
            ListItem lit = new ListItem();
            lit = (ListItem)ddl.Items.FindByValue(ID);
            if (lit != null)
            {
                //Clear the previous selection
                ddl.SelectedIndex = -1;
                lit.Selected = true;
            }
        }

        private void AddGridViewColumns()
        {
            this.GridViewPortfolio.Columns.Clear();
            this.GridViewPortfolio.AutoGenerateColumns = false;

            this.GridViewPortfolio.HeaderStyle.BorderColor = System.Drawing.Color.FromName("#344F3E");

            this.GridViewPortfolio.DataKeyNames = new string[] { "AccID" };
            this.GridViewPortfolio.Columns.Add(new BoundField() { DataField = "AccID", HeaderText = "AccID", Visible = false });

            this.GridViewPortfolio.Columns.Add(new BoundField() { DataField = "ItemID", HeaderText = "Item"});

            TemplateField downloadLinkField = new TemplateField() { HeaderText = "Part Number" };
            downloadLinkField.ItemTemplate = new HyperLinkTemplateColumnForParNumber() { LinkText = "AccPartNum"};
            this.GridViewPortfolio.Columns.Add(downloadLinkField);

            this.GridViewPortfolio.Columns.Add(new BoundField() { DataField = "SAPDesc", HeaderText = "Description" });

            this.GridViewPortfolio.Columns.Add(new BoundField() { DataField = "Inbox", HeaderText = "Inbox" });
            this.GridViewPortfolio.Columns.Add(new BoundField() { DataField = "MG L3", HeaderText = "MG L3" });
        }

        

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            

            btnEdit.Text = "Edit";
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            
        }

        
       

        private void SearchDDLTextFromDataTblAndFillChildDDL(DataTable table, string ddlSelectedText, string ParentColNm, DropDownList Childddl, string ChildColID, String ChildColNm)
        {
            string expression;

            expression = "[" + ParentColNm + "]" + " like " + "'%" + ddlSelectedText.Replace("'", "''") + "%'";
            DataRow[] foundRows;
            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();

                //Create FamilyID and FamilyNm columns for adding to the Datatable
                DataColumn dcol1 = new DataColumn(ChildColID, typeof(System.String));
                dtvalid.Columns.Add(dcol1);
                DataColumn dcol2 = new DataColumn(ChildColNm, typeof(System.String));
                dtvalid.Columns.Add(dcol2);

                foreach (DataRow dr in foundRows)
                {
                    DataRow newRow = dtvalid.NewRow();
                    newRow[ChildColID] = dr[ChildColID].ToString();
                    newRow[ChildColNm] = dr[ChildColNm].ToString();
                    dtvalid.Rows.Add(newRow);

                }

                //return a new table that has only the unique values from the original table dtvalid
                DataTable distinctTable = dtvalid.DefaultView.ToTable( /*distinct*/ true);

                Childddl.Items.Clear();
                int Cntr = 0;
                foreach (DataRow dr in distinctTable.Rows)
                {
                    Childddl.Items.Insert(Cntr, new ListItem(dr[ChildColNm].ToString(), dr[ChildColID].ToString()));
                    Cntr = +1;
                }

                Childddl.Items.Insert(0, new ListItem("Select", "0"));
            }

        }




        protected void btnCopy_Click(object sender, EventArgs e)
        {

        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/LookupAddEditData.aspx?mode={0}&op={1}&row={2}&source={3}", "Compatibility", "edit", 0, "BasicProductInfo"));
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

        }

        protected void btnUndo_Click(object sender, EventArgs e)
        {

        }

        protected void btnRedo_Click(object sender, EventArgs e)
        {

        }

        protected void btnReports_Click(object sender, EventArgs e)
        {

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {

        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            PrepareGridViewForExport(GridViewPortfolio);
            ExportGridView();
        }

        private void ExportGridView()
        {
            VerifyRenderingInServerForm(GridViewPortfolio);

            string attachment = "attachment; filename=" + this.ddlPortfolios.SelectedItem.Text + ".xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            GridViewPortfolio.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }


        private void PrepareGridViewForExport(Control gv)
        {
            LinkButton lb = new LinkButton();
            Literal l = new Literal();
            string name = String.Empty;

            for (int i = 0; i < gv.Controls.Count; i++)
            {
                if (gv.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (gv.Controls[i] as LinkButton).Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                    continue;
                }


                else if (gv.Controls[i].GetType() == typeof(DataControlFieldCell))
                {
                    //l.Text = (gv.Controls[i] as LinkButton).Text;
                    //gv.Controls.Remove(gv.Controls[i]);
                    //gv.Controls.AddAt(i, l);
                    continue;
                }

                else if (gv.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                else if (gv.Controls[i].GetType() == typeof(CheckBox))
                {
                    l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                if (gv.Controls[i].HasControls())
                {
                    PrepareGridViewForExport(gv.Controls[i]);
                }

            }

        }


        protected void btnUpdatePanel_Click(object sender, EventArgs e) 
        { 
        }
        

        protected void btnlstItemCompReset_Click(object sender, EventArgs e)
        {

        }


        protected void btnCompCancel_Click(object sender, EventArgs e)
        {
            //Response.Redirect(string.Format("~/Portfolios.aspx"));
        }

       
        private void PopulateCompatibilityData()
        {            
            SortedCompatibility = SortCompatibility();

            Hashtable hshTableHandhelds = new Hashtable();
            Hashtable hshTableCompatibleHandhelds = new Hashtable();

            string jsCompat = "";

            foreach (KeyValuePair<string, string> c in SortedCompatibility)
            {

                if (c.Value.ToString() == null)
                    continue;
                if (c.Value.IndexOf("XX") > -1)
                    continue;
                else
                {
                    jsCompat = jsCompat + "AddItem('" + lstAllComp.ClientID + "',  '" + c.Value.ToString() + "', '" + c.Key.ToString() + "'); ";
                    hshTableHandhelds.Add(c.Key.ToString(), c.Value.ToString().Replace("'", ""));
                }
            }

            if (dsPortfolios == null)
                dsPortfolios = (DataSet)Session["dsPortfolios"];

            //Fill Compatibility listbox 
            foreach (DataRow dr in dsPortfolios.Tables[COMPATIBILITY].Rows)
            {
                foreach (DataColumn column in dsPortfolios.Tables[COMPATIBILITY].Columns)
                {

                    if ((column.ColumnName != "AccID") && (column.ColumnName != "AccPartNum") && (column.ColumnName != "SAPDesc"))
                    {
                        if ((dr[column.ColumnName].ToString() != " ") && (dr[column.ColumnName].ToString() != ""))
                        {
                            foreach (KeyValuePair<string, string> c in SortedCompatibility)
                            {
                                if (c.Value.ToString() != null)
                                {
                                    if (c.Value.ToString() == column.ColumnName.ToString())
                                    {
                                        //jsCompat = jsCompat + "AddItem('" + lstForThisPartComp.ClientID + "',  '" + column.ColumnName.ToString() + "', '" + c.Key.ToString() + "'); ";
                                        hshTableCompatibleHandhelds.Add(c.Key.ToString(), column.ColumnName.ToString().Replace("'", ""));
                                        //jsCompat = jsCompat + "RemoveItem('" + lstAllComp.ClientID + "',  '" + column.ColumnName.ToString() + "', '" + c.Key.ToString() + "'); ";
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            jsMain = jsMain + jsCompat;            

        }

        private void RetrieveDropDownData()
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();
            dsDropDownPortfolios = rdg.GetDataInfoWithoutParam("GetAllAccParts");
            dsDropDownPortfolios.Tables[0].TableName = PORTFOLIOPARTS;
            Session["dsDropDownPortfolios"] = dsDropDownPortfolios as DataSet;
        }


        public void PopulatePortfolioPartsData()
        {

            if (dsDropDownPortfolios == null)
                dsDropDownPortfolios = (DataSet)Session["dsDropDownPortfolios"];

            if (dsDropDownPortfolios == null)
                RetrieveDropDownData();

            Hashtable hshTablePartsAll = new Hashtable();
            Hashtable hshTablePortfolioParts = new Hashtable();

            string js = "";
            foreach (DataRow row in dsDropDownPortfolios.Tables[PORTFOLIOPARTS].Rows)
            {
                js = js + "AddItem('" + lstAllParts.ClientID + "',  '" + row["AccPartNum"].ToString().Replace("'", "") + "', '" + row["AccID"].ToString() + "'); ";
                hshTablePartsAll.Add(row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", ""));
            }

            //COOAddPanel.Style.Remove("visibility");
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            string PortfolioID = ddlPortfolios.SelectedValue.ToString();

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            //string PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID, "PortfolioID");
                        
            foreach (DataRow row in dsPartsForCurrentPortfolio.Tables[0].Rows)
            {
                foreach (DataColumn column in dsPartsForCurrentPortfolio.Tables[0].Columns)
                {
                    if (column.ColumnName.ToString() == "AccPartNum")
                    {
                        for (int i = 1; i < hshTablePartsAll.Count; i++)
                        {
                            if (hshTablePartsAll[i.ToString()].ToString() == row["AccPartNum"].ToString())
                            {
                                js = js + "AddItem('" + lstPortfolioParts.ClientID + "',  '" + row["AccPartNum"].ToString().Replace("'", "") + "', '" + row["AccID"].ToString() + "'); ";
                                hshTablePortfolioParts.Add(row["AccID"].ToString(), row["AccPartNum"].ToString().Replace("'", ""));
                                js = js + "RemoveItem('" + lstAllParts.ClientID + "',  '" + row["AccPartNum"].ToString().Replace("'", "") + "', '" + row["AccID"].ToString() + "'); ";
                                break;
                            }
                        }
                    }
                }
            }

            js = js + "sortList('" + lstAllParts.ClientID + "'); ";
            js = js + "sortList('" + lstPortfolioParts.ClientID + "'); ";

            jsMain = jsMain + js;

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", js, true);

        }


        

        protected void btnCOOCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/BasicProductInfo.aspx?AccPartNum={0}&editmode={1}", _PartNumber, "edit"));           
        }

        protected void btnAddPartToPortfolioSave_Click(object sender, EventArgs e)
        {
            string PortfolioNm = ddlPortfolios.SelectedItem.Text;// ReturnDDLSelectedItem();

            txtRenamePortfolioName.Text = PortfolioNm;

            string PortfolioID = ddlPortfolios.SelectedValue.ToString();

            //dsPortfolios = (DataSet)Session["dsPortfolios"];
            //DataTable table = dsPortfolios.Tables[PORTFOLIOS];
            //string PortfolioID = SearchDropDownTextIDFromDataTable(table, PortfolioNm, "PortfolioID");

            RetrieveDataGateway rdg = new RetrieveDataGateway();

            rdg.DeletePortfolioPartInfo("DeletePortfolioPartInfo", int.Parse(PortfolioID.ToString()));


            SavePopupPanelData("UpdatePortfolioPartInfo", int.Parse(PortfolioID.ToString()), "PortfolioParts");

            RetrieveData(true);

            dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", PortfolioID.ToString(), "PortfolioID");
            DataTable dt = dsPartsForCurrentPortfolio.Tables[0];
            GridViewPortfolio.DataSource = dt;
            GridViewPortfolio.DataBind();

            lblRecordCount.Text = "Parts found [" + dsPartsForCurrentPortfolio.Tables[0].Rows.Count.ToString() + "]";

            string js = string.Empty;
            js = js + "TriggerAjaxCall()";
            jsMain = jsMain + js;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", jsMain, true);

            //if the user owns the selected portfolio, check if the portfolio contains the current part,
            //if yes, then make the btnAddCurrentPart disabled. If no, then make the btnAddCurrentPart enabled
            bool blnCurrentPartFound = false;
            blnCurrentPartFound = isCurrentPartInPortfolio();
            if (blnCurrentPartFound)
                this.btnAddCurrentPart.Enabled = false;
            else
                this.btnAddCurrentPart.Enabled = true;

            HFlag.Value = "";
                        
        }

        private void SavePopupPanelData(string StoredProc, int PortfolioID, string DataSaved)
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            //get all values added to the listbox for this type from the hidden variable 
            string s = HDestArray.Value;

            if (s != "")
            {
                string[] ListBoxData = s.Split(',');
                foreach (string Data in ListBoxData)
                {
                    switch (DataSaved)
                    {
                        case "PortfolioParts":
                            rdg.UpdatePortfolioInfo(StoredProc, PortfolioID, int.Parse(Data.ToString()));
                            break;
                        default:
                            // Do nothing.
                            break;

                    }

                }
            }
        }
        //protected void btnAddPartToPortfolioCancel_Click(object sender, EventArgs e)
        //{
        //    //Response.Redirect(string.Format("~/BasicProductInfo.aspx?AccPartNum={0}&editmode={1}", _PartNumber, "edit"));
        //}

        private void AddItemsToListBox(ListBox lstForThis, ListBox ListAllItems)
        {
            ArrayList arrayListSelected = arrayListSelected = new ArrayList(ListAllItems.Items.Count);

            for (int i = 0; i < ListAllItems.Items.Count; i++)
                {
                    if (ListAllItems.Items[i].Selected)
                    {
                        lstForThis.Items.Add(ListAllItems.Items[i]);
                        //Add the selected items in the ListAllItems listbox to an array
                        arrayListSelected.Add(ListAllItems.Items[i]);
                    }
                }

            for (int i = 0; i < ListAllItems.Items.Count; i++)
                {
                    for (int j = 0; j < arrayListSelected.Count; j++)
                    {
                        //Remove the items stored in the array from the ListAllItems listbox
                        if (ListAllItems.Items[i].ToString() == arrayListSelected[j].ToString())
                            ListAllItems.Items.Remove(ListAllItems.Items[i]);
                    }
                }
        }

        private void RemoveItemsFromListBox(ListBox lstForThis, ListBox lstAllItems)
        {
            ArrayList arrayListSelected = arrayListSelected = new ArrayList(lstForThis.Items.Count);
            for (int i = 0; i < lstForThis.Items.Count; i++)
            {
                if (lstForThis.Items[i].Selected)
                {

                    lstAllItems.Items.Add(lstForThis.Items[i]);
                    //Add the selected items in the lstForThisPart listbox to an array
                    arrayListSelected.Add(lstForThis.Items[i]);
                }
            }

            for (int i = 0; i < lstForThis.Items.Count; i++)
            {
                for (int j = 0; j < arrayListSelected.Count; j++)
                {
                    //Remove the items stored in the array from the lstAll listbox
                    if (lstForThis.Items[i].ToString() == arrayListSelected[j].ToString())
                        lstForThis.Items.Remove(lstForThis.Items[i]);
                }
            }            
        }

        
        private void SelectListBoxWithData(ListBox lst, string dr)
        {
            ListItem lit = new ListItem();
            lit = (ListItem)lst.Items.FindByText(dr);
            if (lit != null)
            {
                //Clear the previous selection
                lst.SelectedIndex = -1;
                lit.Selected = true;
            }
        }

        

        
        public void SortDropDownList(ListBox dropDownList)
        {
            ArrayList arrayList = arrayList = new ArrayList(dropDownList.Items.Count);
            ArrayList arrayListSelected = arrayListSelected = new ArrayList(dropDownList.Items.Count);

            foreach (ListItem listItem in dropDownList.Items)
            {
                //Store the selected items in the listbox in an array
                if (listItem.Selected)
                    arrayListSelected.Add(listItem);
                arrayList.Add(listItem);
            }


            arrayList.Sort(new ListItemComparer());
            dropDownList.Items.Clear();

            for (int i = 0; i < arrayList.Count; i++)
            {
                dropDownList.Items.Add(arrayList[i].ToString());
                for (int j = 0; j < arrayListSelected.Count; j++)
                {
                    //Retrieve the selected items from the array and make them selected in the listbox after sorting
                    if (arrayList[i].ToString() == arrayListSelected[j].ToString())
                        dropDownList.Items[i].Selected = true;
                }
            }
        }

        public class ListItemComparer : IComparer
        {
            public int Compare(object compareObject1, object compareObject2)
            {
                ListItem listItem1 = (ListItem)compareObject1;
                ListItem listItem2 = (ListItem)compareObject2;

                CaseInsensitiveComparer caseInsensitiveComparer = new CaseInsensitiveComparer();

                return caseInsensitiveComparer.Compare(listItem1.Text, listItem2.Text);
            }
        }

        private List<int> ProcessToSaveListBoxInfo(ListBox lstThisPart, string InfoSaved)
        {
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            // Create a generic list.
            List<int> GenericList = new List<int>();

            DataSet dsSaved = null;

            switch (InfoSaved)
            {
                case "Compatibility":
                    dsSaved = rdg.GetDataInfoWithoutParam("GetHandheldInfo");
                    break;
                case "COO":
                    dsSaved = rdg.GetDataInfoWithoutParam("GetCOOInfo");
                    break;
                case "Restrictions":
                    dsSaved = rdg.GetDataInfoWithoutParam("GetRestrictionsInfo");
                    break;
                case "ECN":
                    dsSaved = rdg.GetDataInfoWithoutParam("GetECNInfo");
                    break;
            }
            
            foreach (ListItem item in lstThisPart.Items)
            {
                int j=0;
                string ItemName = item.Text;

                switch (InfoSaved)
                {
                    case "Compatibility":
                        j = SearchItemInfo(dsSaved.Tables[0], ItemName, "Compatibility");
                        break;
                    case "COO":
                        j = SearchItemInfo(dsSaved.Tables[0], ItemName, "COO");
                        break;
                    case "Restrictions":
                        j = SearchItemInfo(dsSaved.Tables[0], ItemName, "Restrictions");
                        break;
                    case "ECN":
                        j = SearchItemInfo(dsSaved.Tables[0], ItemName, "ECN");
                        break;
                }


                //Add the ItemID to the generic list only if the ItemID is returned from the database
                if (j > 0)
                    GenericList.Add(j);

            }

            return GenericList;

        }


        private List<KeyValuePair<string, string>> SortCompatibility()
        {
            //Fill and sort and return Compatibility info in the form of an array             
            if (dsMaterialHierarchy == null)
                dsMaterialHierarchy = (DataSet)Session["dsMaterialHierarchy"];

            Hashtable hshTableNumericHandheldNames = new Hashtable();

            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();

            RetrieveDataGateway rdg = new RetrieveDataGateway();
            foreach (DataRow row in dsMaterialHierarchy.Tables[COMPATIBILITYHANDHELDCOLUMNS].Rows)
            {

                bool HandheldExist = false;
                string HandheldName = row["Name"].ToString();
                if (_HandheldName != HandheldName)
                    _HandheldName = HandheldName;
                else
                    HandheldExist = true;

                string HandheldID = row["HandheldID"].ToString();
                if (rdg.IsNumeric(row["Name"].ToString()))
                {
                    string HandheldCode = row["Name"].ToString().Substring(0, 2);
                    if (!HandheldExist)
                    {
                        hshTableNumericHandheldNames.Add(HandheldID, HandheldName);
                        list.Add(new KeyValuePair<string, string>(HandheldID, HandheldName));
                    }
                }
                else
                {
                    if (HandheldName.IndexOf("DoCoMo") > -1)
                    {
                        if (!HandheldExist)
                        {
                            hshTableNumericHandheldNames.Add(HandheldID, HandheldName.Substring(7, HandheldName.Length - 7) + " DoCoMo");
                            list.Add(new KeyValuePair<string, string>(HandheldID, HandheldName.Substring(7, HandheldName.Length - 7) + " DoCoMo"));
                        }
                    }
                    else
                    {
                        if (!HandheldExist)
                        {
                            hshTableNumericHandheldNames.Add(HandheldID, HandheldName);
                            list.Add(new KeyValuePair<string, string>(HandheldID, HandheldName));
                        }
                    }
                }
            }


            list.Sort(delegate(KeyValuePair<string, string> y, KeyValuePair<string, string> x) { return string.Compare(x.Value, y.Value); });


            List<KeyValuePair<string, string>> listNew = new List<KeyValuePair<string, string>>();


            foreach (KeyValuePair<string, string> c in list)
            {
                string HandheldCode = c.Value.Substring(0, 2);
                if (rdg.IsNumeric(c.Value))
                {
                    if (!ItemExistsGenericList(listNew, HandheldCode + "XX") && (!ItemExistsGenericList(listNew, c.Value.ToString())))
                    {
                        listNew.Add(new KeyValuePair<string, string>(c.Key, HandheldCode + "XX"));
                    }

                    listNew.Add(new KeyValuePair<string, string>(c.Key, c.Value));
                }
                else
                {
                    if (c.Value.IndexOf("older") > -1)
                    {
                        _HandheldName = c.Key.ToString(); ;
                        continue;
                    }
                    if (c.Value.IndexOf("DoCoMo") > -1)
                    {
                        HandheldCode = c.Value.Substring(0, 2);
                        if (!ItemExistsGenericList(listNew, HandheldCode + "XX") && (!ItemExistsGenericList(listNew, c.Value.ToString())))
                        {
                            listNew.Add(new KeyValuePair<string, string>(c.Key, HandheldCode + "XX"));
                        }

                        listNew.Add(new KeyValuePair<string, string>(c.Key, "DoCoMo " + c.Value.Substring(0, c.Value.Length - 7)));
                    }
                    else
                    {
                        HandheldCode = c.Value.Substring(0, 2);
                        if (rdg.IsNumeric(HandheldCode))
                        {
                            if (!ItemExistsGenericList(listNew, HandheldCode + "XX") && (!ItemExistsGenericList(listNew, c.Value.ToString())))
                            {
                                listNew.Add(new KeyValuePair<string, string>(c.Key, HandheldCode + "XX"));
                            }
                        }
                        listNew.Add(new KeyValuePair<string, string>(c.Key, c.Value));
                    }
                }
            }


            listNew.Add(new KeyValuePair<string, string>(_HandheldName, "older releases"));
            _HandheldName = string.Empty;

            return listNew;

        }

        private bool ItemExists(string[] arr, string itemText)
        {
            bool Exists = false;

            int strNumber;
            for (strNumber = 0; strNumber < arr.Length; strNumber++)
            {
                if (arr[strNumber] == null)
                    continue;
                if (arr[strNumber].IndexOf(itemText) > -1)
                {
                    Exists = true;
                    break;
                }
            }

            return Exists;
        }

        private bool ItemExistsGenericList(List<KeyValuePair<string, string>> GenericList, string itemText)
        {
            bool Exists = false;

            foreach (KeyValuePair<string, string> c in GenericList)
            {
                if (c.Value.ToString() == null)
                    continue;
                if (c.Value.IndexOf(itemText) > -1)
                {
                    Exists = true;
                    break;
                }
            }

            return Exists;
        }


         private int SearchItemInfo(DataTable table, string Item, string InfoSaved)
        {
            string expression=string.Empty;
            string ColumnName = string.Empty;

            switch (InfoSaved)
            {
                case "Compatibility":
                    ColumnName = "HHMktNM";
                    expression = table.Columns[ColumnName].ColumnName + " like " + "'%" + Item + "%'";
                    break;
                case "COO":
                    ColumnName = "CountryNM";
                    expression = table.Columns[ColumnName].ColumnName + " like " + "'%" + Item + "%'";
                    break;
                case "Restrictions":
                    ColumnName = "RestrictionType";
                    expression = table.Columns[ColumnName].ColumnName + " like " + "'%" + Item + "%'";
                    break;
                case "ECN":
                    ColumnName = "ECNNum";
                    expression = table.Columns[ColumnName].ColumnName + " like " + "'%" + Item + "%'";
                    break;    
            }

            
            DataRow[] foundRows;
            // Use the Select method to find all rows matching the filter.
            foundRows = table.Select(expression);

            DataTable dtvalid = null;
            if (foundRows.Length > 0)
            {
                dtvalid = new DataTable();
                dtvalid = table.Clone();

                foreach (DataRow dr in foundRows)
                {
                    //.IndexOf("Bus Admin") > -1
                    if (dr[ColumnName].ToString() == Item)
                    {
                        dtvalid.ImportRow(dr);
                        break;
                    }
                }

            }
            return int.Parse(dtvalid.Rows[0].ItemArray[0].ToString());

        }

        private void ShowMasterPageLinks()
        {
            LinkButton lnk;
            //lnk = (LinkButton)Master.FindControl("lnkSearch");
            //if (lnk != null)
            //{
            //    lnk.Visible = true;
            //}

            lnk = (LinkButton)Master.FindControl("lnkReports");
            if (lnk != null)
            {
                lnk.Visible = true;
            }

            lnk = (LinkButton)Master.FindControl("lnkImages");
            if (lnk != null)
            {
                lnk.Visible = true;

            }

            System.Web.UI.HtmlControls.HtmlAnchor control = Master.SearchLink;
            control.Style.Remove("visibility");
        }

        protected void chkIsPrivate_CheckedChanged(object sender, EventArgs e)
        {
            DataTable dt;
            RetrieveDataGateway rdg = new RetrieveDataGateway();

            _PortfolioIDCurrent =ddlPortfolios.SelectedValue.ToString();//= ReturnPortfolioIDForSelectedPortfolio();
            _PortFolio = ddlPortfolios.SelectedItem.Text.ToString();

            bool blnDoesPortfolioExist = DoesPortfolioExist();

            bool blnIsMyPortFolio = CheckIfIOwnPortfolio();

            if (blnDoesPortfolioExist)//Check if the selected portfolio is public, if true then, if the current
                                      //user owns it, he can change it back to private (there can never be a 
                                      //private portfolio for the same user with the same name)
                _isPublicPortfolio = CheckIfPortfolioIsPublic("CheckedChanged");

            //The current user is not allowed to change a private portfolio to public if another public portfolio 
            //exists with the same name (i.e. if a public portfolio already exists with the same 
            //name, show the error message: "This portfolio name is already in use. Please rename this portfolio and then 
            //make it public"). However, the current user can make his own public portfolio back to private.
            //The current user flag blnIsMyPortFolio should be true in this case and the code will not go into the
            //following IF block of Code below in that case
            if ((blnDoesPortfolioExist) && (_isPublicPortfolio) && (!blnIsMyPortFolio))
            {
                lblPortfolioOwner.Visible = true;
                lblPortfolioOwner.ForeColor = System.Drawing.Color.Red;
                lblPortfolioOwner.Text = "This portfolio name is already in use. Please rename this portfolio and then make it public";
                this.chkIsPrivate.Checked = true;
                SelectDropDownListWithData(this.ddlPortfolios, _PortFolio);

                //get the compatible parts info for the selected handheld                
                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", _PortfolioIDCurrent, "PortfolioID");
                if (dsPartsForCurrentPortfolio.Tables[0].Rows.Count > 0)
                {
                    dt = dsPartsForCurrentPortfolio.Tables[0];
                    GridViewPortfolio.DataSource = dt;
                    GridViewPortfolio.DataBind();
                }
                return;
            }
            else if ((blnDoesPortfolioExist) && (!_isPublicPortfolio) && (blnIsMyPortFolio))
            {
                lblPortfolioOwner.Visible = true;
                lblPortfolioOwner.ForeColor = System.Drawing.Color.Red;
                lblPortfolioOwner.Text = "This portfolio name is already in use. Please rename this portfolio and then make it public";
                this.chkIsPrivate.Checked = true;
                SelectDropDownListWithData(this.ddlPortfolios, _PortFolio);

                //get the compatible parts info for the selected handheld                
                dsPartsForCurrentPortfolio = rdg.GetDataInfoByOneParam("GetPartsForCurrentPortfolio", _PortfolioIDCurrent, "PortfolioID");
                if (dsPartsForCurrentPortfolio.Tables[0].Rows.Count > 0)
                {
                    dt = dsPartsForCurrentPortfolio.Tables[0];
                    GridViewPortfolio.DataSource = dt;
                    GridViewPortfolio.DataBind();
                }
                return;
            }           
           
            bool isPublic = this.chkIsPrivate.Checked == false ? true : false;
            rdg.UpdatePrivacyFlagForSelectedPortfolio("UpdatePrivacyFlagForSelectedPortfolio", _PortfolioIDCurrent, isPublic);
            RetrieveData(true);
            if (!chkIsPrivate.Checked)
            {
                lblPortfolioOwner.Visible = true;
                if (Session["UserLogin"] != null)
                {
                    lblPortfolioOwner.ForeColor = System.Drawing.Color.Green;
                    lblPortfolioOwner.Text = "Owner: " + Session["UserLogin"].ToString();
                }
                else
                    Response.Redirect(string.Format("~/Login.aspx"));
            }
            else
                lblPortfolioOwner.Visible = false;

            AddPortfoliosToDDL();
            _PortFolio = "";
            RetrieveSaveNFillGridWithCurrentPortfolio(IsPostBack, isPublicPortfolioIDontOwn("Load"));
        }
    }


    public class HyperLinkTemplateColumnForParNumber : ITemplate
    {
        public string LinkText { get; set; }

        public HyperLinkTemplateColumnForParNumber() { }

        public void InstantiateIn(Control container)
        {
            HyperLink h = new HyperLink();
            h.DataBinding += new EventHandler(this.OnDataBinding);

            container.Controls.Add(h);
        }

        public void OnDataBinding(object sender, EventArgs e)
        {
            var container = (System.Web.UI.WebControls.HyperLink)sender;
            var dataItem = ((System.Web.UI.WebControls.GridViewRow)container.NamingContainer).DataItem as System.Data.DataRowView;
            if (dataItem != null)
            {
                string sPartNum = dataItem.Row[LinkText].ToString();
                container.NavigateUrl = string.Format("~/Redirect.aspx?url={0}", HttpUtility.UrlEncode("BasicProductInfo.aspx?AccPartNum=" + sPartNum));
                //container.NavigateUrl ="~/BasicProductInfo.aspx?AccPartNum=" + sPartNum;
                //container.NavigateUrl = "javascript:opener.focus();opener.document.location='BasicProductInfo.aspx?AccPartNum=" + sPartNum + "';target=opener;";
                container.Text = dataItem.Row[LinkText].ToString();
                container.Target = "_self";
                container.ForeColor = System.Drawing.Color.Blue;
            }
        }
    }
}

Open in new window

so you are not looping and have one control on your page

ContentPlaceHolder1
and here you have one button... please post the whole code... is this a user control? are you dynamically creating and adding to your page? please post all related codes... this code is not enough to see the whole picture...
As you can see on the top of the aspx page:

MasterPageFile="~/MasterPage.master"

The ContentPlaceHolder1 is from the masterpage. Below is the code for MasterPage.master. However the btnDelete is not at all linked to the Master page and is there in Portfolio.aspx page:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="AccessoriesDBAppSolution.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title id="PageTitleMain" runat="server"></title>
    <script language="javascript" type="text/javascript" src="js/suckerfish-ie-fix.js"></script>
       
    <link href="css/LayoutRoot.css" id="layoutcss" rel="Stylesheet" />
    <link href="css/suckerfish2.css" id="topnavcss" rel="Stylesheet" />
    <link href="css/home.css" id="homecss" rel="Stylesheet" />
    
    
    <asp:ContentPlaceHolder id="head" runat="server"></asp:ContentPlaceHolder>
    <style type="text/css">
        .style1
        {
            width: 773px;
        }
        #header
        {
            height: 32px;
        }
    </style>
</head>
<body id="MasterPageBodyTag" runat="server">
     <form id="form1" runat="server">   
        <div id="wrapper" class="page11">         
            <div id="head2">
                <div id="header" runat="server">
                    A logo img goes here. <br />
                    <table style="height: 7px">
                    <tr><td class="style1"><asp:LinkButton ID="logoutLink" runat="server" Text="Logout" Visible="false" OnClick="logoutLink_Click"></asp:LinkButton></td><td></td>
                    <td><asp:LinkButton ID="lnkSearch" runat="server" Text="Search" Visible="false" OnClick="lnkSearch_Click"></asp:LinkButton>
                    <a href="#" id="SearchLink1" runat="server" onclick="javascript:openSearch(false);" style="visibility:hidden">Search</a></td><td></td>
                    <td><asp:LinkButton ID="lnkReports" runat="server" Text="Reports" Visible="false" OnClick="lnkReports_Click"></asp:LinkButton></td><td></td>
                    <td><asp:LinkButton ID="lnkImages" runat="server" Text="Images" Visible="false" OnClick="lnkImages_Click"></asp:LinkButton></td></tr>
                    </table>
                </div>
            </div>      
                 
            <div id="page">
                <div id="nav" runat="server">
                </div>  <!-- End of Nav Div-->   
                <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>                               
            </div> <!-- End of Page Div -->               
        </div> <!-- End of Wrapper Div-->               
    </form>
</body>
</html>

Open in new window

HainCurt, Do you need any more info to find the clue?
Anyone, please help?
btnAddPart, btnRename are working the way it wanted? I wanted to check those button's enable/disable statements are working as per your code behind.
can you try this?
ASPX:

<button id="btnDelete" type="button" runat="server"  style="height:44px;width:51px;visibility:visible;"
           onclick="ShowPopup('mdlPopupConfirmDeletePortfolio');">Delete</button>

Code behind:
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                this.btnDelete.Style.visibility = "hidden";
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;                
                this.btnDelete.Style.visibility = "visible";
}

Open in new window

I am getting the following error and it does not compile:

System.Web.UI.CssStyleCollection' does not contain a definition for 'visibility' and no extension method 'visibility' accepting a first argument of type 'System.Web.UI.CssStyleCollection' could be found (are you missing a using directive or an assembly reference?

BTW btnAddPart, btnRename are working the way they are wanted. Note that btnAddPart is an ASP server side button control, so no issue with it. For the btnRename, an html button similar to the btnDelete, the only thing to note is that it is contained in an <asp:UpdatePanel> (please view the code above). On the other hand, the btnDelete is an html button control that is not inside an Update Panel. Does thta make a difference?
are you able to call "btnDelete.Disabled = false" as the same way btnRename?
if yes, the Panel doe NOT make any difference, but if not, the Panel is MAKING some problem
yes I can go to the if else block of code and can see the code executed and falling through either block correctly (see below), however at the end the button is always enabled in both cases (wheteher if or else block).
bool blnIsMyPortFolio = CheckIfIOwnPortfolio(PortfolioID);
            if (!blnIsMyPortFolio)
            {
                this.btnRename.Disabled = true;
                this.btnAddPart.Enabled = false;
                this.btnAddCurrentPart.Enabled = false;
                btnDelete.Disabled=true;
            }
            else
            {
                this.btnRename.Disabled = false;
                this.btnAddPart.Enabled = true;

                btnDelete.Disabled=false;
}

Open in new window

Please note that in case of btnRename, everything works as expected i.e the button is disabled for the if block of code and enabled for the else block of code. Can you see the aspx for both buttons and compare, may be you can find a clue that I can not until now:
ASKER CERTIFIED SOLUTION
Avatar of Roshan Davis
Roshan Davis
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
just a guess try.

can you try

Page.ClientScript.RegisterStartupScript(this.GetType(), "clientscript", "document.getElementById('btnDelete').style.visibility = 'hidden';" ,true);

Open in new window

Roshmon,
Thanks a lot, the culprit is the update panel. When I added the btnDelete in a separate Update Panel, the btnDelete is disabled/enabled as desired. Let me check and test that in more detail and I will get back to you tommorrow.
Thanks Roshmon