Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Data lost on submit

Posted on 2010-08-23
24
Medium Priority
?
920 Views
Last Modified: 2013-12-17
Dear Experts,

I have a modal popup and a GridView in it. The GridView is populated programmatically, i.e. I use .DataBind(). I can enter data into some of the GridView's controls. After I press Submit, I expect to do something with the entered data. But in the button press handler, the GridView is empty. I realize that I have to DataBind() again in the handler, but how can I preserve the data the user enters?

Thanks.
0
Comment
Question by:tantormedia
  • 12
  • 8
  • 2
  • +1
24 Comments
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33500152
I am not sure how you are creating and working with the modal popup, but it sounds like there is a postback happening which is wiping the state of the gridview before your button handler method is fired.
0
 
LVL 14

Expert Comment

by:Dhanasekaran Sengodan
ID: 33500198
can u post sample code?
0
 

Author Comment

by:tantormedia
ID: 33500220
Here is my code:

...

        DataTable submitOfferTable = new DataTable();
        DataColumn columnEAN = new DataColumn("EAN", Type.GetType("System.String"));
        columnEAN.Unique = true;
        submitOfferTable.Columns.Add(columnEAN);
        DataColumn columnOfferDate = new DataColumn("OfferDate", Type.GetType("System.DateTime"));
        submitOfferTable.Columns.Add(columnOfferDate);
        DataColumn columnAmount = new DataColumn("Amount", Type.GetType("System.Double"));
        submitOfferTable.Columns.Add(columnAmount);
        DataColumn columnExpirationDate = new DataColumn("ExpirationDate", Type.GetType("System.DateTime"));
        submitOfferTable.Columns.Add(columnExpirationDate);

        foreach (string EAN in keys.Keys)
        {
            DataRow submitOfferRow = submitOfferTable.NewRow();
            submitOfferRow["EAN"] = EAN;
            submitOfferRow["OfferDate"] = DateTime.Now;
            submitOfferRow["Amount"] = keys[EAN].Amount;
            submitOfferRow["ExpirationDate"] = (keys[EAN].Date == DateTime.MinValue) ? DateTime.MinValue : keys[EAN].Date.AddDays(63);   // by default, expiration date is PubDate + 9 weeks

            submitOfferTable.Rows.Add(submitOfferRow);
        }

        SubmitOfferGridView.DataSource = submitOfferTable;
        SubmitOfferGridView.DataBind();

        SubmitOfferModalPopupExtender.Show();

Open in new window

0
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 

Author Comment

by:tantormedia
ID: 33500230
SandyAgo,

I understand that postback does that, I just would like to know how to avoid this problem.
0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33500322
Ok. So that is the code to bind the data and show the popup, what do you do during the button click handler?
0
 

Author Comment

by:tantormedia
ID: 33500341
Here:

foreach (GridViewRow row in SubmitOfferGridView.Rows)
        {
// This is skipped because there are no rows in the GridView
...
}

Open in new window

0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33500467
Is your first piece of code within an event or within the Page_load? Also where do you bind the data agin in the handler? i dont think you should need to bind the data again, because it should be added to the viewstate of the page during the postback.
0
 

Author Comment

by:tantormedia
ID: 33500507
The first piece of code is within a method that handles click of a button (not in the modal popup, but in the main form), that shows the modal popup.
There is no data binding in the popup submit handler.
0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33500926
Ok. I really am not sure what is happening from your descriptions. i have attached some simple code which works for me. Maybe it will help to find the problem.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test1.aspx.cs" Inherits="Test.test1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxToolkit" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
    
    <div>
    
        <asp:Panel ID="modalpop" runat="server">
            <asp:GridView ID="SubmitOfferGridView" runat="server"></asp:GridView>
            <asp:Button ID="PostButton" runat="server" Text="post back" OnClick="Post_Click" />
        </asp:Panel>
        
        <asp:Button ID="pbutton" runat="server" Text="show" onclick="PButton_Click"/>
        
        <asp:Button style="display: none;" ID="activate" runat="server" Text="activate" />
        
        <AjaxToolkit:ModalPopupExtender ID="SubmitOfferModalPopupExtender" runat="server" TargetControlID="activate" PopupControlID="modalpop"/>
    </div>
    </form>
</body>
</html>


<!-- code behind -->


using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
    public partial class test1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {



        }

        public void PButton_Click(object sender, EventArgs e)
        {
            DataTable submitOfferTable = new DataTable();
            DataColumn columnEAN = new DataColumn("EAN", Type.GetType("System.String"));
            columnEAN.Unique = true;
            submitOfferTable.Columns.Add(columnEAN);
            DataColumn columnOfferDate = new DataColumn("OfferDate", Type.GetType("System.DateTime"));
            submitOfferTable.Columns.Add(columnOfferDate);
            DataColumn columnAmount = new DataColumn("Amount", Type.GetType("System.Double"));
            submitOfferTable.Columns.Add(columnAmount);
            DataColumn columnExpirationDate = new DataColumn("ExpirationDate", Type.GetType("System.DateTime"));
            submitOfferTable.Columns.Add(columnExpirationDate);

            for (int i = 0; i < 10; i++)
            {
                DataRow submitOfferRow = submitOfferTable.NewRow();
                submitOfferRow["EAN"] = "EAN" + i;
                submitOfferRow["OfferDate"] = DateTime.Now;
                submitOfferRow["Amount"] = 70.0;
                submitOfferRow["ExpirationDate"] = DateTime.Now;   // by default, expiration date is PubDate + 9 weeks 

                submitOfferTable.Rows.Add(submitOfferRow);
            }

            SubmitOfferGridView.DataSource = submitOfferTable;
            SubmitOfferGridView.DataBind();

            SubmitOfferModalPopupExtender.Show();
        }

        public void Post_Click(object sender, EventArgs e)
        {
            int rows = 0;
            foreach (GridViewRow row in SubmitOfferGridView.Rows)
            {
                rows++;
            }

            SubmitOfferModalPopupExtender.Hide();
        }
    }
}

Open in new window

0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33500948
in the above sample,  rows comes out to 10 after clicking post back. Good Luck.
0
 

Author Comment

by:tantormedia
ID: 33500996
Strange, I don't see any particular difference between your code and mine... and yet mine doesn't work...
0
 

Author Comment

by:tantormedia
ID: 33503426
Can it have anything to do with the fact that my modal popup is in a user control?
0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33506478
I dont think so. I moved the code into a UC and it still works for me. I will post and you can see if there are any differences.
ascx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test.Controls
{
    public partial class ModPop : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void PButton_Click(object sender, EventArgs e)
        {
            DataTable submitOfferTable = new DataTable();
            DataColumn columnEAN = new DataColumn("EAN", Type.GetType("System.String"));
            columnEAN.Unique = true;
            submitOfferTable.Columns.Add(columnEAN);
            DataColumn columnOfferDate = new DataColumn("OfferDate", Type.GetType("System.DateTime"));
            submitOfferTable.Columns.Add(columnOfferDate);
            DataColumn columnAmount = new DataColumn("Amount", Type.GetType("System.Double"));
            submitOfferTable.Columns.Add(columnAmount);
            DataColumn columnExpirationDate = new DataColumn("ExpirationDate", Type.GetType("System.DateTime"));
            submitOfferTable.Columns.Add(columnExpirationDate);

            for (int i = 0; i < 10; i++)
            {
                DataRow submitOfferRow = submitOfferTable.NewRow();
                submitOfferRow["EAN"] = "EAN" + i;
                submitOfferRow["OfferDate"] = DateTime.Now;
                submitOfferRow["Amount"] = 70.0;
                submitOfferRow["ExpirationDate"] = DateTime.Now;   // by default, expiration date is PubDate + 9 weeks 

                submitOfferTable.Rows.Add(submitOfferRow);
            }

            SubmitOfferGridView.DataSource = submitOfferTable;
            SubmitOfferGridView.DataBind();

            SubmitOfferModalPopupExtender.Show();
        }

        public void Post_Click(object sender, EventArgs e)
        {
            int rows = 0;
            foreach (GridViewRow row in SubmitOfferGridView.Rows)
            {
                rows++;
            }
            string user = UserName.Text;
            SubmitOfferModalPopupExtender.Hide();
        }
    }
}


ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ModPop.ascx.cs" Inherits="CRM.Controls.ModPop" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AjaxToolkit" %>

<asp:Button ID="pbutton" runat="server" Text="show" onclick="PButton_Click"/>
<asp:Button style="display: none;" ID="activate" runat="server" Text="activate" />

<asp:Panel ID="modalpop" runat="server">
    <asp:GridView ID="SubmitOfferGridView" runat="server" >
    </asp:GridView>
        <asp:TextBox ID="UserName" runat="server" />
    <asp:Button ID="PostButton" runat="server" OnClick="Post_Click" 
        Text="post back" />
        

</asp:Panel>

<AjaxToolkit:ModalPopupExtender ID="SubmitOfferModalPopupExtender" runat="server" TargetControlID="activate" PopupControlID="modalpop"/>


test1.aspx becomes

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test1.aspx.cs" Inherits="CRM.test1" %>
<%@ Register TagPrefix="uc" TagName="modpop" Src="~/Controls/ModPop.ascx" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
    
    <div>
    

        
        
        <uc:modpop ID="modalpop" runat="server" />
    
        
        
    </div>
    </form>
</body>
</html>

Open in new window

0
 

Author Comment

by:tantormedia
ID: 33531551
Why can it be that the ViewState doesn't preserve my data? And how can I debug to see at what stage the ViewState loses the information?

Thanks.
0
 

Author Comment

by:tantormedia
ID: 33534102
I copied your code into my page, and the result was the save as with my code... :(
0
 
LVL 2

Expert Comment

by:SandyAgo
ID: 33537757
Can you post the whole 4 pieces of code (aspx, aspx.cs, ascx, ascx.cs)?
0
 

Author Comment

by:tantormedia
ID: 33541160

Here:
Default.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TPS" validaterequest="false" EnableEventValidation="false" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <link type="text/css" href="StyleSheet.css" rel="stylesheet" />
    <style type="text/css">
        table { table-layout: fixed; 
            margin-top: 7px;
        }
        #form
        {
            height: 391px;
            width: 9803px;
        }

    </style>
    <script type="text/javascript" src="Scripts/getElementsByClassName-1.0.1.js"></script> 
    <script type="text/javascript" src="Scripts/ResizableGridView.js"></script> 
    <script type="text/javascript" src="Scripts/Cookies.js"></script> 
        
    <script type="text/javascript">
    
        function MoveItem(ctrlSource, ctrlTarget, buttonUp, buttonDown, hiddenField) {
            var Source = document.getElementById(ctrlSource);
            var Target = document.getElementById(ctrlTarget);

            if ((Source != null) && (Target != null)) {
                while (Source.options.selectedIndex >= 0) {
                    var HiddenList = document.getElementById(hiddenField);  //The hidden field
                    var SelectedValue = Source.options[Source.options.selectedIndex].value + ','; // Hidden List is comma seperated
                    var newOption = new Option(); // Create a new instance of ListItem
                    newOption.text = Source.options[Source.options.selectedIndex].text;
                    newOption.value = Source.options[Source.options.selectedIndex].value;

                    Target.options[Target.length] = newOption; //Append the item in Target
                    Source.remove(Source.options.selectedIndex);  //Remove the item from Source
                    if (HiddenList.value.indexOf(SelectedValue) == -1) {
                        HiddenList.value += SelectedValue; // Add it to hidden list
                    }
                    else {
                        HiddenList.value = HiddenList.value.replace(SelectedValue, ""); // Remove from Hidden List
                        UpDownEnableDisable(ctrlSource, buttonUp, buttonDown);
                    }
                }
            }
        }

        function SwapItem(listBox, itemPos, swapPos, hiddenField, buttonUp, buttonDown) {
            var lb = document.getElementById(listBox);
            var HiddenList = document.getElementById(hiddenField);

            // First swap values in hidden SelectedItems field
            HiddenList.value = HiddenList.value.replace(lb.options[swapPos].value, "placeholder");
            HiddenList.value = HiddenList.value.replace(lb.options[itemPos].value, lb.options[swapPos].value);
            HiddenList.value = HiddenList.value.replace("placeholder", lb.options[itemPos].value);
            
            var tempOption = new Array(lb.options[swapPos].text, lb.options[swapPos].value);
            lb.options[swapPos].text = lb.options[itemPos].text;
            lb.options[swapPos].value = lb.options[itemPos].value;
            lb.options[itemPos].text = tempOption[0];
            lb.options[itemPos].value = tempOption[1];
            lb.selectedIndex = swapPos;

            UpDownEnableDisable(listBox, buttonUp, buttonDown);
        }

        function MoveDown(listBox, hiddenField, buttonUp, buttonDown) {
            var lb = document.getElementById(listBox);
            if (lb.selectedIndex < lb.options.length - 1) {
                SwapItem(listBox, lb.selectedIndex, lb.selectedIndex + 1, hiddenField, buttonUp, buttonDown);
            }                
        }

        function MoveUp(listBox, hiddenField, buttonUp, buttonDown) {
            var lb = document.getElementById(listBox); 
            if(lb.selectedIndex > 0)
                SwapItem(listBox, lb.selectedIndex, lb.selectedIndex - 1, hiddenField, buttonUp, buttonDown);
        }

        function UpDownEnableDisable(listBox, buttonUp, buttonDown) {
            var lb = document.getElementById(listBox);
            var btnUp = document.getElementById(buttonUp);
            if (lb.selectedIndex == 0 || lb.selectedIndex == -1)
                btnUp.disabled = true;
            else
                btnUp.disabled = false;

            var btnDown = document.getElementById(buttonDown);
            if (lb.selectedIndex == lb.options.length - 1 || lb.selectedIndex == -1)
                btnDown.disabled = true;
            else
                btnDown.disabled = false;
        }

        function ClearSortFields(hiddenField) {
            var HiddenList = document.getElementById(hiddenField);  //The hidden field
            HiddenList.value = "";
        }
      
    </script>
    
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="DefaultContentPlaceHolder" Runat="Server">
    
    <ajaxToolkit:TabContainer ID="tcTPS" runat="server" 
        ActiveTabIndex="0" onactivetabchanged="tcTPS_ActiveTabChanged" 
        AutoPostBack="true" > 
        <ajaxToolkit:TabPanel runat="server" HeaderText="Licensing" ID="LicensingTabPanel" Width="100%" >        
            <HeaderTemplate>
                Licensing
            </HeaderTemplate>
            <ContentTemplate> 
		        <asp:PlaceHolder ID="LicensingPlaceHolder" runat="server" />
            </ContentTemplate>     
        </ajaxToolkit:TabPanel>  

...
    </ajaxToolkit:TabContainer>              
    <script type="text/javascript" >
        document.onkeypress = keyPressHandler;
    </script>      
</asp:Content>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Data;
using System.Web.UI.HtmlControls;
using Yogesh.ExcelXml;
using System.Drawing;
using System.Text;
using System.Data.Odbc;

public partial class TPS : BasePage
{
    protected void Page_Init(object sender, EventArgs e)
    {
        LoadUserControl();
    }

    private void LoadUserControl()
    {
        int tpsActiveTabIndex = 0;
        if (Session["tpsActiveTabIndex"] == null)
        {
            tpsActiveTabIndex = tcTPS.ActiveTabIndex;
        }
        else
        {
            tpsActiveTabIndex = tcTPS.ActiveTabIndex = Convert.ToInt32(Session["tpsActiveTabIndex"]);
        }

        switch (tpsActiveTabIndex)
        {
            case 0:
                UserControl uc1 = (UserControl)Page.LoadControl("~/Licensing.ascx");
                LicensingPlaceHolder.Controls.Add(uc1);
                this.AddGridViewClasses(uc1.Controls);
                break;
            case 1:
                UserControl uc2 = (UserControl)Page.LoadControl("~/Production.ascx");
                ProductionPlaceHolder.Controls.Add(uc2);
                this.AddGridViewClasses(uc2.Controls);
                break;
            case 2:
                UserControl uc3 = (UserControl)Page.LoadControl("~/Marketing.ascx");
                MarketingPlaceHolder.Controls.Add(uc3);
                this.AddGridViewClasses(uc3.Controls);
                break;
            case 3:
                UserControl uc4 = (UserControl)Page.LoadControl("~/Database.ascx");
                DatabasePlaceHolder.Controls.Add(uc4);
                this.AddGridViewClasses(uc4.Controls);
                break;
            default:
                break;
        }
        this.Page.Header.Controls.Add(new StyleTag() { FontSize = this.FontSize });
    }


    protected void tcTPS_ActiveTabChanged(object sender, EventArgs e)
    {
        Session["tpsActiveTabIndex"] = tcTPS.ActiveTabIndex;
        LoadUserControl();
    }
}
 

Licensing.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Licensing.ascx.cs" Inherits="Licensing" %>
<%@ Register Assembly="skmValidators" Namespace="skmValidators" TagPrefix="cc1" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

    <script type="text/javascript">
        function ShowImportErrors() {
            setTimeout("$find('ShowImportErrors').show();", 1000);
        }
        function ShowCustomViewErrors() {
            setTimeout("$find('ShowCustomViewErrors').show();", 5000);
        }
        function ShowLicensingDetailErrors() {
            setTimeout("$find('ShowLicensingDetailErrors').show();", 5000);
        }

        function keyPressHandler(e) {
            var kC = (window.event) ?    // MSIE or Firefox
                 event.keyCode : e.keyCode;
            var Esc = (window.event) ?
                27 : e.DOM_VK_ESCAPE;    // MSIE or Firefox
            var Enter = (window.event) ?
                13 : e.DOM_VK_RETURN;     // MSIE or Firefox
            if (kC == Enter) {
                var btnFilter = document.getElementById('<%=btnFilter.ClientID %>');
                if (btnFilter != null) {
                    btnFilter.click();
                    return false;
                }
            }
            else if (kC == Esc) {
                // add code when needed to handle Esc
            }
        }             
    </script>
       
    <asp:SqlDataSource ID="UserSqlDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:BookList %>" 
        ProviderName="<%$ ConnectionStrings:BookList.ProviderName %>" SelectCommand="SELECT ID, Name FROM User WHERE Name <> '*All' ORDER BY Name;" >
    </asp:SqlDataSource>       

    <asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="filter"
    BorderStyle="Solid" HeaderText="The following error(s) occured:" />
    <br />
    <br />
    
    <asp:Button ID="btnAddNew" runat="server" Text="Add New" Width="100px" onclick="btnAddNew_Click"  />

    <a href="Print/PrintLicensing.aspx" target="_blank">Print</a> 
       
    <asp:DropDownList ID="ddlFilter" runat="server" AutoPostBack="True" 
        Height="20px" style="margin-right:20px" Width="227px" 
        CausesValidation="True" onselectedindexchanged="btnFilter_OnClick" >
            <asp:ListItem Text="All" Value="-2" Selected="True" />
            <asp:ListItem Text="My Titles" Value="-1" />
            <asp:ListItem Text="Cancelled Titles" Value="0" />
            <asp:ListItem Text="On Offer" Value="1" />
            <asp:ListItem Text="For Consideration" Value="2" />
            <asp:ListItem Text="Make Offer" Value="3" />
            <asp:ListItem Text="On Hold" Value="4" />     
            <asp:ListItem Text="Titles from Existing Authors" Value="5" />                       
    </asp:DropDownList>
    <asp:Button ID="btnCustomViews" runat="server" Text="Custom Views" Width="100px" onclick="btnCustomViews_Click"  />
    <asp:DropDownList ID="ddlBookQuestFields" runat="server" Height="20px" 
        Width="350px"  >
    </asp:DropDownList>    
     <asp:TextBox ID="txtFilterValue" runat="server" ValidationGroup="filter" ></asp:TextBox>    
    <asp:CustomValidator ID="filterValidator" runat="server" onservervalidate="Custom_ServerValidate"
        ControlToValidate="txtFilterValue" ErrorMessage="Populated Dynamically" ValidationGroup="filter" ValidateEmptyText="true" >* </asp:CustomValidator>    
    <asp:Button ID="btnFilter" runat="server" Text="Search" OnClick="btnFilter_OnClick" ValidationGroup="filter" />                          
    <asp:Button ID="btnSetSort" runat="server" Text="Set Sort" Width="100px" onclick="btnSetSort_Click" />
    <asp:Button ID="btnFilterByLicensors" runat="server" Text="Filter By Licensors" onclick="btnFilterByLicensors_Click" />    
    <asp:Button ID="btnHideColumns" runat="server" Text="Hide Columns" Width="100px" onclick="btnHideColumns_Click" />
    <br /><br />
    <asp:DropDownList ID="ddlDatesToFilterBy" runat="server" AutoPostBack="True" 
        Height="20px" style="margin-right:20px" Width="227px" ValidationGroup="filter" 
        CausesValidation="True" onselectedindexchanged="btnFilter_OnClick" >
            <asp:ListItem Text="Pub Date" Value="b.PubDate" Selected="True" />
            <asp:ListItem Text="Offer Date" Value="bo.OfferDate" />
            <asp:ListItem Text="Last Date" Value="b.LastDate" />
            <asp:ListItem Text="First Appearance" Value="b.FirstAppearance" />
    </asp:DropDownList>  

    From
    <asp:ImageButton ID="imgBtnFrom" runat="server" 
        AlternateText="Click here to display calendar" 
        ImageUrl="~/Images/Calendar_scheduleHS.png" />
    <asp:TextBox ID="From" runat="server"></asp:TextBox>
    <ajaxToolkit:CalendarExtender ID="FromCE" runat="server" Enabled="True" 
        PopupButtonID="imgBtnFrom" TargetControlID="From">
    </ajaxToolkit:CalendarExtender>
    <asp:CompareValidator ID="FromCompareValidator" runat="server" 
        ControlToValidate="From" Display="Dynamic" ErrorMessage="Invalid From Date!" Text="*"
        Operator="DataTypeCheck" Type="Date" ValidationGroup="filter"></asp:CompareValidator>
    <ajaxToolkit:ValidatorCalloutExtender ID="FromCompareValidator_ValidatorCalloutExtender" 
        runat="server" Enabled="True" TargetControlID="FromCompareValidator">
    </ajaxToolkit:ValidatorCalloutExtender>
    To
    <asp:ImageButton ID="imgBtnTo" runat="server" 
        AlternateText="Click here to display calendar" 
        ImageUrl="~/Images/Calendar_scheduleHS.png" />
    <asp:TextBox ID="To" runat="server"></asp:TextBox>
    <ajaxToolkit:CalendarExtender ID="ToCE" runat="server" Enabled="True" 
        PopupButtonID="imgBtnTo" TargetControlID="To">
    </ajaxToolkit:CalendarExtender>
    <asp:CompareValidator ID="ToCompareValidator" runat="server" 
        ControlToValidate="To" Display="Dynamic" ErrorMessage="Invalid To Date!" Text="*"
        Operator="DataTypeCheck" Type="Date" ValidationGroup="filter"></asp:CompareValidator>
    <ajaxToolkit:ValidatorCalloutExtender ID="ToValidatorCalloutExtender" 
        runat="server" Enabled="True" TargetControlID="ToCompareValidator">
    </ajaxToolkit:ValidatorCalloutExtender>    

    <asp:SqlDataSource ID="LicensorsSqlDataSource" runat="server" 
    ConnectionString="<%$ ConnectionStrings:BookList %>" 
        ProviderName="<%$ ConnectionStrings:BookList.ProviderName %>" SelectCommand="SELECT DISTINCT Licensor FROM BookQuest WHERE Licensor <> '' ORDER BY Licensor;" >
    </asp:SqlDataSource>    


    <asp:Panel ID="pnlSubmitOffer" runat="server" CssClass="modalPopup" Style="display:none" Width="700px" >
        <asp:GridView ID="SubmitOfferGridView" runat="server" AllowSorting="True"
                AutoGenerateColumns="False" 
                Width="100%" Height="306px" DataKeyNames="EAN" >
            <AlternatingRowStyle CssClass="alternatingrowstyle" />
            <Columns>
                <asp:BoundField DataField="EAN" HeaderText="EAN" SortExpression="EAN" />
                <asp:TemplateField HeaderText="Offer Date" SortExpression="OfferDate">
                    <ItemTemplate>   
                        <asp:ImageButton runat="Server" ID="imgBtnOfferDate" 
                            ImageUrl="~/Images/Calendar_scheduleHS.png" 
                            AlternateText="Click here to display calendar" />
                        <asp:TextBox ID="OfferDate" runat="server" 
                            Text='<%# Bind("OfferDate","{0:M/d/yyyy}") %>'></asp:TextBox>
                        <ajaxToolkit:CalendarExtender ID="OfferDateCE" runat="server" 
                            TargetControlID="OfferDate" PopupButtonID="imgBtnOfferDate"/>                                
                        <asp:CompareValidator ID="OfferDateCompareValidator" runat="server" 
                            ControlToValidate="OfferDate" Display="Dynamic" 
                            ErrorMessage="Invalid OfferDate!" Text="*" Operator="DataTypeCheck" 
                            Type="Date"></asp:CompareValidator>
                        <ajaxToolkit:ValidatorCalloutExtender ID="OfferDateCompareValidator_ValidatorCalloutExtender" 
                            runat="server" Enabled="True" TargetControlID="OfferDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                    </ItemTemplate>
                </asp:TemplateField>   
                <asp:TemplateField HeaderText="Amount" SortExpression="Amount">
                    <ItemTemplate>    
                        <asp:TextBox ID="Amount" runat="server" Text='<%#Bind("Amount") %>'></asp:TextBox>
                        <asp:CompareValidator ID="AmountCompareValidator" runat="server" 
                            ControlToValidate="Amount" Display="Dynamic" 
                            ErrorMessage="Amount has invalid currency value!" Text="*" 
                            Operator="DataTypeCheck" Type="Currency"></asp:CompareValidator>
                    </ItemTemplate>
                </asp:TemplateField>    
                <asp:TemplateField HeaderText="Expiration Date" SortExpression="ExpirationDate">
                    <ItemTemplate>   
                        <asp:ImageButton runat="Server" ID="imgBtnExpirationDate" 
                            ImageUrl="~/Images/Calendar_scheduleHS.png" 
                            AlternateText="Click here to display calendar" />
                        <asp:TextBox ID="ExpirationDate" runat="server" 
                            Text='<%# Bind("ExpirationDate","{0:M/d/yyyy}") %>'></asp:TextBox>
                        <ajaxToolkit:CalendarExtender ID="ExpirationDateCE" runat="server" 
                            TargetControlID="ExpirationDate" PopupButtonID="imgBtnExpirationDate"/>                                
                        <asp:CompareValidator ID="ExpirationDateCompareValidator" runat="server" 
                            ControlToValidate="ExpirationDate" Display="Dynamic" 
                            ErrorMessage="Invalid ExpirationDate!" Text="*" Operator="DataTypeCheck" 
                            Type="Date"></asp:CompareValidator>
                        <ajaxToolkit:ValidatorCalloutExtender ID="ExpirationDateCompareValidator_ValidatorCalloutExtender" 
                            runat="server" Enabled="True" 
                            TargetControlID="ExpirationDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                    </ItemTemplate>
                </asp:TemplateField>                                                  
            </Columns>
            <HeaderStyle CssClass="headerstyle" />
        </asp:GridView> 

        <div align="center">
            <asp:Button ID="btnSubmitSubmitOffer" runat="server" Text="Submit" OnClick="btnSubmitSubmitOffer_Click" />
            <asp:Button ID="btnCancelSubmitOffer" runat="server" Text="Cancel" />
        </div>
    </asp:Panel>
    
    <asp:Panel ID="pnlOnHold" runat="server" CssClass="modalPopup" Style="display:none" Width="400px" >
        <p>
        Please enter your comments:
       </p>  
        <div align="center">  
            <asp:TextBox ID="txtOnHoldComment" runat="server" TextMode="MultiLine" Width="350px" Height="100px" MaxLength="255" ></asp:TextBox>
        </div>  
        <div align="center">
            <asp:Button ID="btnSubmitOnHold" runat="server" Text="Submit" OnClick="btnSubmitOnHold_Click" />
            <asp:Button ID="btnCancelOnHold" runat="server" Text="Cancel" />
        </div>
    </asp:Panel>
    
    <asp:Panel ID="pnlAssignTitle" runat="server" CssClass="modalPopup" Style="display:none" Width="200px" >
        <p>
            Please select a user:
        </p>  
        <div align="center">  
            <asp:DropDownList ID="ddlUser" runat="server" DataSourceID="UserSqlDataSource" DataTextField="Name" DataValueField="ID" >
            </asp:DropDownList>
        </div>                                
        <br /><br />
        <div align="center">
            <asp:Button ID="btnSubmitAssignTitle" runat="server" Text="Submit" OnClick="btnSubmitAssignTitle_Click" />
            <asp:Button ID="btnCancelAssignTitle" runat="server" Text="Cancel" />
        </div> 
    </asp:Panel>
    
    <asp:Panel ID="pnlCancel" runat="server" CssClass="modalPopup" Style="display:none" Width="1000px" >
        <asp:GridView ID="CancelGridView" runat="server" AllowSorting="True"
                AutoGenerateColumns="False" 
                Width="100%" Height="306px" DataKeyNames="EAN" >
            <AlternatingRowStyle CssClass="alternatingrowstyle" />
            <Columns>
                <asp:BoundField DataField="EAN" HeaderText="EAN" SortExpression="EAN" />
                <asp:TemplateField HeaderText="Cancellation Reason" SortExpression="Reason">
                    <ItemTemplate>    
                        <asp:DropDownList ID="Reason" runat="server" >
                            <asp:ListItem Selected="True" Text="Outbid" Value="0"></asp:ListItem>
                            <asp:ListItem Text="Not Available" Value="1"></asp:ListItem> 
                            <asp:ListItem Text="Withdrawn" Value="2"></asp:ListItem>                         
                        </asp:DropDownList>                                
                    </ItemTemplate>                    
                </asp:TemplateField>                            
                <asp:TemplateField HeaderText="Comments" SortExpression="Comments">
                    <ItemTemplate>    
                        <asp:TextBox ID="Comments" runat="server" Width="100%" MaxLength="255" ></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle CssClass="headerstyle" />
        </asp:GridView> 

        <div align="center">
            <asp:Button ID="btnSubmitCancel" runat="server" Text="Submit" OnClick="btnSubmitCancel_Click" />
            <asp:Button ID="btnCancelCancel" runat="server" Text="Cancel" />
        </div>        
    </asp:Panel>
    
    <asp:Panel ID="pnlImport" runat="server" CssClass="modalPopup" Style="display:none" Width="800px" >
        <asp:ValidationSummary ID="ImportValidationSummary" runat="server" ValidationGroup="ImportValidation" 
            BorderStyle="Solid" HeaderText="The following error(s) occured:" />       
        <p>
        Select a file to import:
       </p>  
        <div align="center">  
            <asp:FileUpload ID="importFilePath" runat="server" Height="27px" Size="80" />
            <asp:RequiredFieldValidator 
                 id="importFilePathRequiredFieldValidator" runat="server" 
                 ErrorMessage="You must enter path for the import file!" Text="*" 
                 ControlToValidate="importFilePath" ValidationGroup="ImportValidation" >
                 </asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator 
                 id="importFilePathRegularExpressionValidator" runat="server" 
                 ErrorMessage="Only xls and xlsx files are allowed!" Text="*" 
                 ValidationExpression="^.*\.(xls|XLS|xlsx|XLSX)$" 
                 ControlToValidate="importFilePath" ValidationGroup="ImportValidation" >
                 </asp:RegularExpressionValidator>       
            <asp:CustomValidator ID="HasFileCustomValidator" runat="server" ControlToValidate="importFilePath" OnServerValidate="HasFileCustomValidate" 
                ErrorMessage="No File Supplied!" Text="*"  ValidationGroup="ImportValidation"></asp:CustomValidator>    
            <br />
            <div align="center" style="vertical-align:middle;width:350px">  
                 <p>
                Please select publishers whose books you wish to import:
                </p>   
                <asp:SqlDataSource ID="PublisherSqlDataSource" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:BookList %>" 
                    ProviderName="<%$ ConnectionStrings:BookList.ProviderName %>" SelectCommand="SELECT ID, Name FROM Publisher ORDER BY Name;" >
                </asp:SqlDataSource>       
                
                <div style="overflow:auto; height:200px; overflow:auto;">
                    <asp:CheckBoxList ID="chlstPublishers" runat="server"
                        DataSourceID="PublisherSqlDataSource" DataTextField="Name" DataValueField="ID"  
                        Width="100%" >
                    </asp:CheckBoxList>
                </div>
                <cc1:CheckBoxListValidator ID="chlstPublishersCheckBoxListValidator" ControlToValidate="chlstPublishers" Text="*" ErrorMessage="You did not select any publisher." MinimumNumberOfSelectedCheckBoxes="1" ValidationGroup="ImportValidation" runat="server"></cc1:CheckBoxListValidator>
                <br />
                Select <a id="A3" href="#" onclick="javascript: CheckBoxListSelect ('<%= chlstPublishers.ClientID %>',true)">All</a>
                | <a id="A4" href="#" onclick="javascript: CheckBoxListSelect ('<%= chlstPublishers.ClientID %>',false)">None</a>                    
            </div>         
        </div>  
        <div align="center">
            <asp:TextBox ID="txtError" runat="server" Text="Set Dynamically" Visible="false" TextMode="MultiLine" CssClass="Warning" BackColor="Transparent" BorderStyle="None" Width="700px"></asp:TextBox>
            <br />
            <asp:Button ID="btnSubmitImport" runat="server" Text="Import" OnClick="btnSubmitImport_Click" ValidationGroup="ImportValidation" />
            <asp:Button ID="btnCancelImport" runat="server" Text="Cancel" />
        </div>
    </asp:Panel>    
    
    <asp:Panel ID="pnlOrderBy" runat="server" CssClass="modalPopup" Style="display:none" Width="500px" >
        <p>
        Select columns to sort by:
        </p>  
        <div align="center" style="vertical-align:middle;">  
            <table style="width: 100%;">
                <tr>
                    <td align="center" style="height:450px;width:130px;">
                        <asp:ListBox ID="lstSourceFields" runat="server" Height="450px" Width="130px" ></asp:ListBox>
                    </td>
                    <td align="center" style="height:450px;width:40px;">
                        <input onclick="Javascript:MoveItem('<%= lstSourceFields.ClientID %>', '<%= lstSelectedFields.ClientID %>', 'btnUp', 'btnDown', '<%= SelectedItems.ClientID %>');" type="button" value="->" />
                        <br />
                        <input onclick="Javascript:MoveItem('<%= lstSelectedFields.ClientID %>', '<%= lstSourceFields.ClientID %>', 'btnUp', 'btnDown', '<%= SelectedItems.ClientID %>');" type="button" value="<-" />
                    </td>
                    <td align="center" style="height:450px;width:130px;">
                        <asp:ListBox ID="lstSelectedFields" runat="server" Height="450px" Width="130px" onclick="Javascript:UpDownEnableDisable(this.id, 'btnUp', 'btnDown');"></asp:ListBox>
                    </td>
                    <td align="left" style="height:450px;width:40px;">
                        <input id="btnUp"   type="button" value="Up"   disabled="disabled" style="width:50px" onclick="Javascript:MoveUp('<%= lstSelectedFields.ClientID %>','<%= SelectedItems.ClientID %>', 'btnUp', 'btnDown')" />
                        <br />
                        <input id="btnDown" type="button" value="Down" disabled="disabled" style="width:50px" onclick="Javascript:MoveDown('<%= lstSelectedFields.ClientID %>','<%= SelectedItems.ClientID %>', 'btnUp', 'btnDown')" />
                    </td>                                                
                </tr>
            </table>
        
        </div>  
        <br />
        <div align="center">
            <asp:Button ID="btnSubmitOrderBy" runat="server" Text="Submit" OnClick="btnSubmitOrderBy_Click" />
            <input id="btnCancelOrderBy" type="button" value="Cancel" onclick="Javascript:ClearSortFields('<%= SelectedItems.ClientID %>')" />
        </div>
        
        <asp:HiddenField ID="SelectedItems" runat="server" /> 
    </asp:Panel>    
    
    <asp:Panel ID="pnlHideColumns" runat="server" CssClass="modalPopup" Style="display:none" Width="300px" >
        <p>
        Select columns to hide:
        </p>  
        <div align="center">  
            <asp:ListBox ID="lstFields" runat="server" Height="450px" Width="130px" SelectionMode="Multiple"></asp:ListBox>
            <br /><br />
            <input id="btnHideColumnsClearAll" type="button" value="Clear All" onclick="document.getElementById('<%=lstFields.ClientID %>').selectedIndex=-1;" />
            <br /><br />

            <asp:Button ID="btnSubmitHideColumns" runat="server" Text="Submit" OnClick="btnSubmitHideColumns_Click" />
            <asp:Button ID="btnCancelHideColumns" runat="server" Text="Cancel" />
        </div>

    </asp:Panel>    

    <asp:Panel ID="pnlFilterByLicensors" runat="server" CssClass="modalPopup" Style="display:none" Width="300px" >
        <p>
        Select licensors to filter by:
        </p>  
        <div align="center">  
            <asp:ListBox ID="lstLicensors" runat="server" Height="450px" Width="130px" SelectionMode="Multiple"
                DataSourceID="LicensorsSqlDataSource" DataTextField="Licensor" DataValueField="Licensor" >
            </asp:ListBox>
            <br /><br />
            <input id="btnFilterByLicensorsClearAll" type="button" value="Clear All" onclick="document.getElementById('<%=lstLicensors.ClientID %>').selectedIndex=-1;" />
            <br /><br />

            <asp:Button ID="btnSubmitFilterByLicensors" runat="server" Text="Submit" OnClick="btnSubmitFilterByLicensors_Click" />
            <asp:Button ID="btnCancelFilterByLicensors" runat="server" Text="Cancel" />
        </div>

    </asp:Panel>    

    <asp:Panel ID="pnlCustomViews" runat="server" CssClass="modalPopup" Style="display:none" Width="850px" >
        <div align="center" style="vertical-align:middle;">  
            Custom View Name:
            <asp:TextBox ID="txtCustomViewName" runat="server" Width="200px" ValidationGroup="customview" ></asp:TextBox> 
            <asp:RadioButton id="rdoPublic"  Text="Public"  GroupName="PrivateOrPublic" runat="server" Checked="True"/>
            <asp:RadioButton id="rdoPrivate" Text="Private" GroupName="PrivateOrPublic" runat="server"/> 
            <br /> 
            <asp:RequiredFieldValidator 
                 id="CVNameRequiredFieldValidator" runat="server" 
                 ErrorMessage="You must enter name for the new custom view!" 
                 ControlToValidate="txtCustomViewName" ValidationGroup="customview" >
                 </asp:RequiredFieldValidator>  
                 <br /><br />
            <asp:DropDownList ID="ddlCVBookQuestFields" runat="server" Height="20px" 
                Width="200px"  >
            </asp:DropDownList>    
            <asp:TextBox ID="txtCVFilterValue" runat="server" ValidationGroup="customview" ></asp:TextBox>    
            <asp:CustomValidator ID="cvFilterValidator" runat="server" onservervalidate="ValidateCustomViews"
                ControlToValidate="txtCVFilterValue" ErrorMessage="Populated Dynamically" ValidationGroup="customview" ValidateEmptyText="true" ></asp:CustomValidator>    
            <br /><br />
                 
            <table style="margin:0px;">
                <tr>
                    <td colspan="3" align="center" style="width:360px;">
                        Select columns to sort by:
                    </td>
                    <td align="left" style="width:130px;"></td>
                    <td align="center" style="width:150px;">
                        Select fields to hide:
                    </td>
                    <td align="center" style="width:170px;">
                        Select licensors to filter by:
                    </td>                    
                </tr>
                <tr style="height:400px" valign="top">
                    <td align="center" style="width:150px;">
                        <asp:ListBox ID="lstCustomViewsSourceFields" runat="server" Height="350px" Width="150px" ></asp:ListBox>
                    </td>
                    <td align="center" style="width:60px;">
                        <input onclick="Javascript:MoveItem('<%= lstCustomViewsSourceFields.ClientID %>', '<%= lstCustomViewsSelectedFields.ClientID %>', 'btnUp', 'btnDown', '<%= SelectedItems.ClientID %>');" type="button" value="->" />
                        <br />
                        <input onclick="Javascript:MoveItem('<%= lstCustomViewsSelectedFields.ClientID %>', '<%= lstCustomViewsSourceFields.ClientID %>', 'btnUp', 'btnDown', '<%= SelectedItems.ClientID %>');" type="button" value="<-" />
                    </td>
                    <td align="center" style="width:150px;">
                        <asp:ListBox ID="lstCustomViewsSelectedFields" runat="server" Height="350px" Width="150px" onclick="Javascript:UpDownEnableDisable(this.id, 'btnCustomViewsUp', 'btnCustomViewsDown');"></asp:ListBox>
                    </td>
                    <td align="left" style="width:130px;">
                        <input id="btnCustomViewsUp"   type="button" value="Up"   disabled="disabled" style="width:50px" onclick="Javascript:MoveUp('<%= lstCustomViewsSelectedFields.ClientID %>','<%= SelectedItems.ClientID %>', 'btnCustomViewsUp', 'btnCustomViewsDown')" />
                        <br />
                        <input id="btnCustomViewsDown" type="button" value="Down" disabled="disabled" style="width:50px" onclick="Javascript:MoveDown('<%= lstCustomViewsSelectedFields.ClientID %>','<%= SelectedItems.ClientID %>', 'btnCustomViewsUp', 'btnCustomViewsDown')" />
                    </td>  
                    <td align="center" style="width:150px;">
                        <asp:ListBox ID="lstCustomViewsFields" runat="server" Height="350px" Width="150px" SelectionMode="Multiple" ></asp:ListBox>
                        <br /><br />
                        <input id="btnCVFieldsClearAll" type="button" value="Clear All" onclick="document.getElementById('<%=lstCustomViewsFields.ClientID %>').selectedIndex=-1;" />
                    </td>   
                    <td align="center" style="width:150px;">
                        <asp:ListBox ID="lstCustomViewsLicensors" runat="server" Height="350px" Width="150px" SelectionMode="Multiple" 
                            DataSourceID="LicensorsSqlDataSource" DataTextField="Licensor" DataValueField="Licensor" >
                        </asp:ListBox>
                        <br /><br />
                        <input id="btnCVLicensorsClearAll" type="button" value="Clear All" onclick="document.getElementById('<%=lstCustomViewsLicensors.ClientID %>').selectedIndex=-1;" />
                    </td>                                                                   
                </tr>
            </table>
        </div>  
        <br />
        <div align="center">
            <asp:TextBox ID="txtCVError" runat="server" Text="Set Dynamically" Visible="false" TextMode="MultiLine" CssClass="Warning" BackColor="Transparent" BorderStyle="None" Width="500px"></asp:TextBox>
            <br />
            <asp:Button ID="btnSaveCustomViews" runat="server" Text="Save" OnClick="btnSaveCustomViews_Click" CausesValidation="true" ValidationGroup="customview" />
            <asp:Button ID="btnSaveAndApplyCustomViews" runat="server" Text="Save and Apply" OnClick="btnSaveAndApplyCustomViews_Click" CausesValidation="true" ValidationGroup="customview" />
            <input id="btnCancelCustomViews" type="button" value="Cancel" onclick="Javascript:ClearSortFields('<%= SelectedItems.ClientID %>')" />
        </div>
        
    </asp:Panel>    

    <ajaxToolkit:ModalPopupExtender ID="SubmitOfferModalPopupExtender" runat="server" TargetControlID="btnShowSubmitOfferPopup" PopupControlID="pnlSubmitOffer" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelSubmitOffer" >
    </ajaxToolkit:ModalPopupExtender>    
    <ajaxToolkit:ModalPopupExtender ID="OnHoldModalPopupExtender"      runat="server" TargetControlID="btnShowPutOnHoldPopup"   PopupControlID="pnlOnHold"      BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelOnHold" >
    </ajaxToolkit:ModalPopupExtender>
    <ajaxToolkit:ModalPopupExtender ID="AssignTitleModalPopupExtender" runat="server" TargetControlID="btnShowAssignTitlePopup" PopupControlID="pnlAssignTitle" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelAssignTitle" >
    </ajaxToolkit:ModalPopupExtender>    
    <ajaxToolkit:ModalPopupExtender ID="CancelModalPopupExtender"      runat="server" TargetControlID="btnShowCancelPopup"      PopupControlID="pnlCancel"      BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelCancel" >
    </ajaxToolkit:ModalPopupExtender> 
    <ajaxToolkit:ModalPopupExtender ID="ImportModalPopupExtender"      runat="server" TargetControlID="btnShowImportPopup"      PopupControlID="pnlImport"      BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelImport" BehaviorID="ShowImportErrors" >
    </ajaxToolkit:ModalPopupExtender>     
    <ajaxToolkit:ModalPopupExtender ID="OrderByModalPopupExtender"     runat="server" TargetControlID="btnShowOrderByPopup"     PopupControlID="pnlOrderBy"     BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelOrderBy" >
    </ajaxToolkit:ModalPopupExtender>  
    <ajaxToolkit:ModalPopupExtender ID="HideColumnsModalPopupExtender" runat="server" TargetControlID="btnShowHideColumnsPopup" PopupControlID="pnlHideColumns" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelHideColumns" >
    </ajaxToolkit:ModalPopupExtender>   
    <ajaxToolkit:ModalPopupExtender ID="FilterByLicensorsModalPopupExtender" runat="server" TargetControlID="btnShowFilterByLicensorsPopup" PopupControlID="pnlFilterByLicensors" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelFilterByLicensors" >
    </ajaxToolkit:ModalPopupExtender>            
    <ajaxToolkit:ModalPopupExtender ID="CustomViewsModalPopupExtender" runat="server" TargetControlID="btnShowCustomViewsPopup" PopupControlID="pnlCustomViews" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancelCustomViews" BehaviorID="ShowCustomViewErrors" >
    </ajaxToolkit:ModalPopupExtender>          
    
    <asp:SqlDataSource ID="FrontListSqlDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:BookList %>" DataSourceMode="DataSet" 
        ProviderName="<%$ ConnectionStrings:BookList.ProviderName %>" 
        UpdateCommand="UPDATE BookQuest SET `TantorStatus` = ?, `AssignedTo` = ?, `Title` = ?, `RespParty` = ?, `Publisher` = ?, `PubDate` = ?, `Subject` = ?, `Binding` = ?, `PageCount` = ?, `USListPrice` = ?, `Demand` = ?, `OnOrder` = ?, `OnBackorder` = ?, `SpeedStock` = ?, `Status` = ?, `BTKey` = ?, `FirstPrinting` = ?, `Ingram` = ?, `Licensor` = ?, `LastDate` = ?, `Comments` = ?, `Note` = ?, `FirstAppearance` = ?, `Material` = ?, `UnitSales` = ? WHERE `EAN` = ?;"
    >
        <UpdateParameters>
            <asp:Parameter Name="TantorStatus" Type="Int32" />
            <asp:Parameter Name="AssignedTo" Type="Int32" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="RespParty" Type="String" />
            <asp:Parameter Name="Publisher" Type="String" />
            <asp:Parameter Name="PubDate" Type="DateTime" />
            <asp:Parameter Name="Subject" Type="String" />
            <asp:Parameter Name="Binding" Type="String" />
            <asp:Parameter Name="PageCount" Type="Int32" />
            <asp:Parameter Name="USListPrice" Type="Double" />
            <asp:Parameter Name="Demand" Type="Int32" />
            <asp:Parameter Name="OnOrder" Type="Int32" />
            <asp:Parameter Name="OnBackorder" Type="Int32" />
            <asp:Parameter Name="SpeedStock" Type="Int32" />
            <asp:Parameter Name="Status" Type="String" />
            <asp:Parameter Name="BTKey" Type="Int32" />
            <asp:Parameter Name="FirstPrinting" Type="Int32" />
            <asp:Parameter Name="Ingram" Type="String" />
            <asp:Parameter Name="Licensor" Type="String" />
            <asp:Parameter Name="LastDate" Type="DateTime" />
            <asp:Parameter Name="Comments" Type="String" />
            <asp:Parameter Name="Note" Type="String" />
            <asp:Parameter Name="FirstAppearance" Type="DateTime" />
            <asp:Parameter Name="Material" Type="String" />
            <asp:Parameter Name="UnitSales" Type="Int32" />
            <asp:Parameter Name="EAN" Type="String" />
        </UpdateParameters>    
    </asp:SqlDataSource>

		<table class="largegridview" cellspacing="0" rules="all" border="1" id="FrontListGridViewHeader" runat="server" style="height:100%;width:2880px;border-collapse:collapse;">
			<tr class="headerstyle">
				<th scope="col" style="width:20px; color:transparent;">*</th><th scope="col">EAN</th><th scope="col">TantorStatus</th><th scope="col">Assigned To</th><th scope="col">Title</th><th scope="col">RespParty</th><th scope="col">Publisher</th><th scope="col">PubDate</th><th scope="col">Subject</th><th scope="col">Binding</th><th scope="col">Page Count</th><th scope="col">US List Price</th><th scope="col">Demand</th><th scope="col">On Order</th><th scope="col">On Backorder</th><th scope="col">SpeedStock</th><th scope="col">Status</th><th scope="col">BTKey</th><th scope="col">First Printing</th><th scope="col">Ingram</th><th scope="col">Licensor</th><th scope="col">Offer Date</th><th scope="col">Offer Amount</th><th scope="col">Last Date</th><th scope="col">Comments</th><th scope="col">Instructions</th><th scope="col">First Appearance</th><th scope="col">Material</th><th scope="col">Unit Sales</th>
			</tr>    
		</table>
		<div style="height:400px; width:2900px; overflow:auto;">
            <asp:GridView ID="FrontListGridView" runat="server" AllowSorting="False" ShowFooter="False" ShowHeader="false"
                        AllowPaging="True" PageSize="100" DataSourceID="FrontListSqlDataSource" 
                        AutoGenerateColumns="False" Width="2880px" Height="100%" 
                        OnRowDataBound="FrontListGridView_RowDataBound" 
                        OnRowCommand="FrontListGridView_RowCommand"
                        CssClass="largegridview largegridview_td" DataKeyNames="EAN" >        
                <AlternatingRowStyle CssClass="alternatingrowstyle" />
                <HeaderStyle CssClass="headerstyle" />
                
                <Columns>
                     <asp:TemplateField HeaderText="Color" SortExpression="Color">
                        <ItemTemplate>
                            <asp:Label ID="lblColor" runat="server" Text='<%# Eval("Color") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                 
                     
                     <asp:TemplateField>
                        <ItemTemplate>
                             <asp:CheckBox ID="BookSelector" runat="server" >
                             </asp:CheckBox>
                        </ItemTemplate>
                     </asp:TemplateField>  
                     
                     <asp:ButtonField Text="SingleClick" CommandName="Select" Visible="False" />

                     <asp:TemplateField HeaderText="EAN" SortExpression="EAN">
                        <ItemTemplate>
                            <asp:Label ID="lblEAN" runat="server" Text='<%# Eval("EAN") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                     
                     <asp:TemplateField HeaderText="TantorStatus" SortExpression="TantorStatus">
                        <EditItemTemplate>    
                            <asp:DropDownList ID="TantorStatus" runat="server" SelectedValue='<%# Server.HtmlDecode(Convert.IsDBNull(Eval("TantorStatusNumber")) ? string.Empty : Convert.ToString(Eval("TantorStatusNumber")))%>' >
                                <asp:ListItem Text="" Value=""></asp:ListItem>
                                <asp:ListItem Text="Canceled" Value="0"></asp:ListItem>
                                <asp:ListItem Text="On Offer" Value="1"></asp:ListItem> 
                                <asp:ListItem Text="For Consideration" Value="2"></asp:ListItem>    
                                <asp:ListItem Text="Make Offer" Value="3"></asp:ListItem>    
                                <asp:ListItem Text="On Hold" Value="4"></asp:ListItem>    
                            </asp:DropDownList>                       
                        </EditItemTemplate>                     
                        <ItemTemplate>                    
                            <asp:Label ID="lblTantorStatus" runat="server" Text='<%# Eval("TantorStatus") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                
                    
                     <asp:TemplateField HeaderText="Assigned To" SortExpression="AssignedTo">
                        <EditItemTemplate>    
                            <asp:DropDownList ID="AssignedTo" runat="server" SelectedValue='<%# Server.HtmlDecode(Convert.IsDBNull(Eval("AssignedToNumber")) ? string.Empty : (Eval("AssignedToNumber")).ToString())%>'
                                DataSourceID="UserSqlDataSource" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true" >
                                <asp:ListItem Text="" Value=""></asp:ListItem>
                            </asp:DropDownList>                       
                        </EditItemTemplate>                   
                        <ItemTemplate>
                            <asp:Label ID="lblAssignTo" runat="server" Text='<%# Eval("AssignedTo") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>  
                    
                     <asp:TemplateField HeaderText="Title" SortExpression="Title">
                        <EditItemTemplate>    
                            <asp:TextBox ID="Title" runat="server" Text='<%# Eval("Title") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                    
                        <ItemTemplate>
                            <asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                                  
                    <asp:TemplateField HeaderText="RespParty" SortExpression="RespParty">
                        <EditItemTemplate>    
                            <asp:TextBox ID="RespParty" runat="server" Text='<%# Eval("RespParty") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                  
                        <ItemTemplate>
                            <asp:Label ID="lblRespParty" runat="server" Text='<%# Eval("RespParty") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>               
                     
                    <asp:TemplateField HeaderText="Publisher" SortExpression="Publisher">
                        <EditItemTemplate>    
                            <asp:TextBox ID="Publisher" runat="server" Text='<%# Eval("Publisher") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                   
                        <ItemTemplate>
                            <asp:Label ID="lblPublisher" runat="server" Text='<%# Eval("Publisher") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                    
                     
                    <asp:TemplateField HeaderText="PubDate" SortExpression="PubDate">
                        <EditItemTemplate>    
                            <asp:TextBox ID="PubDate" runat="server" Text='<%# Eval("PubDate","{0:M/d/yyyy}") %>' Width="70px" ></asp:TextBox>
                            <asp:ImageButton runat="Server" ID="imgBtnPubDate" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                            <ajaxToolkit:CalendarExtender ID="PubDateCE" runat="server" TargetControlID="PubDate" PopupButtonID="imgBtnPubDate"/>                                
                            <asp:CompareValidator ID="PubDateCompareValidator" runat="server" ControlToValidate="PubDate" Display="Dynamic" ErrorMessage="Invalid PubDate!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="filter" ></asp:CompareValidator>
                            <ajaxToolkit:ValidatorCalloutExtender ID="PubDateCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="PubDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                       </EditItemTemplate>                  
                        <ItemTemplate>
                            <asp:Label ID="lblPubDate" runat="server" Text='<%#Eval("PubDate","{0:M/d/yyyy}") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="Subject" SortExpression="Subject">
                        <EditItemTemplate>    
                            <asp:TextBox ID="Subject" runat="server" Text='<%# Eval("Subject") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                   
                        <ItemTemplate>
                            <asp:Label ID="lblSubject" runat="server" Text='<%# Eval("Subject") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                  
                     
                    <asp:TemplateField HeaderText="Binding" SortExpression="Binding">
                        <EditItemTemplate>    
                            <asp:TextBox ID="Binding" runat="server" Text='<%# Eval("Binding") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                   
                        <ItemTemplate>
                            <asp:Label ID="lblBinding" runat="server" Text='<%# Eval("Binding") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="Page Count" SortExpression="PageCount">
                        <EditItemTemplate>    
                            <asp:TextBox ID="PageCount" runat="server" Text='<%# Eval("PageCount") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="PageCountCompareValidator" runat="server" ControlToValidate="PageCount" Display="Dynamic" ErrorMessage="Page Count must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                   
                        <ItemTemplate>
                            <asp:Label ID="lblPageCount" runat="server" Text='<%# Eval("PageCount") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                     <asp:TemplateField HeaderText="US List Price" SortExpression="USListPrice">
                        <EditItemTemplate>    
                            <asp:TextBox ID="USListPrice" runat="server" Text='<%# Eval("USListPrice") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="USListPriceCompareValidator" runat="server" ControlToValidate="USListPrice" Display="Dynamic" ErrorMessage="US List Price has invalid currency value!" Text="*" Operator="DataTypeCheck" Type="Currency" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:Label ID="lblUSListPrice" runat="server" Text='<%# Eval("USListPrice","{0:c}") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                  
                     
                    <asp:TemplateField HeaderText="Demand" SortExpression="Demand">
                        <EditItemTemplate>    
                            <asp:TextBox ID="Demand" runat="server" Text='<%# Eval("Demand") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="DemandCompareValidator" runat="server" ControlToValidate="Demand" Display="Dynamic" ErrorMessage="Demand must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:Label ID="lblDemand" runat="server" Text='<%# Eval("Demand") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="On Order" SortExpression="OnOrder">
                        <EditItemTemplate>    
                            <asp:TextBox ID="OnOrder" runat="server" Text='<%# Eval("OnOrder") %>' Width="100%"></asp:TextBox>
                            <asp:CompareValidator ID="OnOrderCompareValidator" runat="server" ControlToValidate="OnOrder" Display="Dynamic" ErrorMessage="On Order must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:Label ID="lblOnOrder" runat="server" Text='<%# Eval("OnOrder") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                     <asp:TemplateField HeaderText="On Backorder" SortExpression="OnBackorder">
                       <EditItemTemplate>    
                            <asp:TextBox ID="OnBackorder" runat="server" Text='<%# Eval("OnBackorder") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="OnBackorderCompareValidator" runat="server" ControlToValidate="OnBackorder" Display="Dynamic" ErrorMessage="On Backorder must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:Label ID="lblOnBackorder" runat="server" Text='<%# Eval("OnBackorder") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                  
                     
                     <asp:TemplateField HeaderText="SpeedStock" SortExpression="SpeedStock">
                       <EditItemTemplate>    
                            <asp:CheckBox ID="SpeedStock" runat="server" Checked='<%# Eval("SpeedStock") %>' /> 
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:CheckBox ID="lblSpeedStock" runat="server" Checked='<%# Eval("SpeedStock") %>' Enabled="false" /> 
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                     <asp:TemplateField HeaderText="Status" SortExpression="Status">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Status" runat="server" Text='<%# Eval("Status") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                       
                        <ItemTemplate>                    
                            <asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Status") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="BTKey" SortExpression="BTKey">
                       <EditItemTemplate>    
                            <asp:TextBox ID="BTKey" runat="server" Text='<%# Eval("BTKey") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="BTKeyCompareValidator" runat="server" ControlToValidate="BTKey" Display="Dynamic" ErrorMessage="BTKey must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                       
                        <ItemTemplate>
                            <asp:Label ID="lblBTKey" runat="server" Text='<%# Eval("BTKey") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="First Printing" SortExpression="FirstPrinting">
                       <EditItemTemplate>    
                            <asp:TextBox ID="FirstPrinting" runat="server" Text='<%# Eval("FirstPrinting") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="FirstPrintingCompareValidator" runat="server" ControlToValidate="FirstPrinting" Display="Dynamic" ErrorMessage="FirstPrinting must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                  
                        <ItemTemplate>
                            <asp:Label ID="lblFirstPrinting" runat="server" Text='<%# Eval("FirstPrinting") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                    
                     
                     <asp:TemplateField HeaderText="Ingram" SortExpression="Ingram">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Ingram" runat="server" Text='<%# Eval("Ingram") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                  
                        <ItemTemplate>                    
                            <asp:Label ID="lblIngram" runat="server" Text='<%# Eval("Ingram") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                       
                     
                     <asp:TemplateField HeaderText="Licensor" SortExpression="Licensor">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Licensor" runat="server" Text='<%# Eval("Licensor") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                  
                        <ItemTemplate>                    
                            <asp:Label ID="lblLicensor" runat="server" Text='<%# Eval("Licensor") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                   
                     
                    <asp:TemplateField HeaderText="Offer Date" SortExpression="OfferDate">
                        <ItemTemplate>
                            <asp:Label ID="lblOfferDate" runat="server" Text='<%#Eval("OfferDate","{0:M/d/yyyy}") %>' Enabled="false"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField> 
                    
                     <asp:TemplateField HeaderText="Offer Amount" SortExpression="OfferAmount">
                        <ItemTemplate>
                            <asp:Label ID="lblOfferAmount" runat="server" Text='<%# Eval("OfferAmount","{0:c}") %>' Enabled="false"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                                        
                     
                    <asp:TemplateField HeaderText="Last Date" SortExpression="LastDate">
                       <EditItemTemplate>    
                            <asp:TextBox ID="LastDate" runat="server" Text='<%# Eval("LastDate","{0:M/d/yyyy}") %>' Width="70px" ></asp:TextBox>
                            <asp:ImageButton runat="Server" ID="imgBtnLastDate" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                            <ajaxToolkit:CalendarExtender ID="LastDateCE" runat="server" TargetControlID="LastDate" PopupButtonID="imgBtnLastDate"/>                                
                            <asp:CompareValidator ID="LastDateCompareValidator" runat="server" ControlToValidate="LastDate" Display="Dynamic" ErrorMessage="Invalid Last Date!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="filter" ></asp:CompareValidator>
                            <ajaxToolkit:ValidatorCalloutExtender ID="LastDateCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="LastDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                       </EditItemTemplate>                 
                        <ItemTemplate>
                            <asp:Label ID="lblLastDate" runat="server" Text='<%#Eval("LastDate","{0:M/d/yyyy}") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                  
                     
                     <asp:TemplateField HeaderText="Comments" SortExpression="Comments">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Comments" runat="server" Text='<%# Eval("Comments") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                   
                        <ItemTemplate>                    
                            <asp:Label ID="lblComments" runat="server" Text='<%# Eval("Comments") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                    
                     
                     <asp:TemplateField HeaderText="Instructions" SortExpression="Instructions">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Instructions" runat="server" Text='<%# Eval("Note") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                   
                        <ItemTemplate>                    
                            <asp:Label ID="lblInstructions" runat="server" Text='<%# Eval("Note") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                  
                     
                    <asp:TemplateField HeaderText="First Appearance" SortExpression="FirstAppearance">
                       <EditItemTemplate>    
                            <asp:TextBox ID="FirstAppearance" runat="server" Text='<%# Eval("FirstAppearance","{0:M/d/yyyy}") %>' Width="70px"></asp:TextBox>
                            <asp:ImageButton runat="Server" ID="imgBtnFirstAppearance" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                            <ajaxToolkit:CalendarExtender ID="FirstAppearanceCE" runat="server" TargetControlID="FirstAppearance" PopupButtonID="imgBtnFirstAppearance"/>                                
                            <asp:CompareValidator ID="FirstAppearanceCompareValidator" runat="server" ControlToValidate="FirstAppearance" Display="Dynamic" ErrorMessage="Invalid First Appearance Date!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="filter" ></asp:CompareValidator>
                            <ajaxToolkit:ValidatorCalloutExtender ID="FirstAppearanceCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="FirstAppearanceCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                       </EditItemTemplate>                  
                        <ItemTemplate>
                            <asp:Label ID="lblFirstAppearance" runat="server" Text='<%#Eval("FirstAppearance","{0:M/d/yyyy}") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                     
                     
                     <asp:TemplateField HeaderText="Material" SortExpression="Material">
                       <EditItemTemplate>    
                            <asp:TextBox ID="Material" runat="server" Text='<%# Eval("Material") %>' Width="100%" ></asp:TextBox>
                       </EditItemTemplate>                  
                        <ItemTemplate>                    
                            <asp:Label ID="lblMaterial" runat="server" Text='<%# Eval("Material") %>' ></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField> 
                    
                    <asp:TemplateField HeaderText="Unit Sales" SortExpression="UnitSales">
                       <EditItemTemplate>    
                            <asp:TextBox ID="UnitSales" runat="server" Text='<%# Eval("UnitSales") %>' Width="100%" ></asp:TextBox>
                            <asp:CompareValidator ID="UnitSalesCompareValidator" runat="server" ControlToValidate="UnitSales" Display="Dynamic" ErrorMessage="Unit Sales must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="filter" ></asp:CompareValidator>
                       </EditItemTemplate>                  
                        <ItemTemplate>
                            <asp:Label ID="lblUnitSales" runat="server" Text='<%# Eval("UnitSales") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                    
                </Columns>

        </asp:GridView> 
        </div>

        <asp:Panel ID="pnlLicensingDetail" runat="server" CssClass="modalPopup" DefaultButton="btnLicensingDetailSubmit"
            Style="display:none" Width="700px" >
            <ContentTemplate>           
                <div align="center" style="vertical-align:middle; height:600px; overflow:auto">
                    <br />
                    <asp:ValidationSummary ID="LicensingDetailValidationSummary" runat="server" ValidationGroup="licensing_validation" 
                        BorderStyle="Solid" HeaderText="The following error(s) occured:" />   
                        
                    <asp:Button ID="btnShowLicensingDetailPopup" runat="server" style="display:none" />            
                        
                    <ajaxToolkit:ModalPopupExtender ID="LicensingDetailModalPopupExtender" 
                        runat="server" TargetControlID="btnShowLicensingDetailPopup" 
                        PopupControlID="pnlLicensingDetail" BackgroundCssClass="modalBackground" 
                        DropShadow="True" CancelControlID="btnLicensingDetailCancel" DynamicServicePath="" 
                        Enabled="True" BehaviorID="ShowLicensingDetailErrors" ></ajaxToolkit:ModalPopupExtender>                   
                          
                    <table id="LicensingDetail" style="width:600px; text-align:left">
                    
                        <tr>
                            <td style="width:20%;">EAN</td>
                            <td>
                                <asp:TextBox ID="EAN" runat="server" Width="80%" ></asp:TextBox>
                                <asp:RequiredFieldValidator ID="EANRequiredFieldValidator" runat="server" Text="*"
                                    ErrorMessage="EAN is a required field." ControlToValidate="EAN" ValidationGroup="licensing_validation" >
                                </asp:RequiredFieldValidator>                                
                            </td>
                        </tr>                      
                        <tr>
                            <td style="width:20%;">TantorStatus</td>
                            <td>
                                <asp:DropDownList ID="TantorStatus" runat="server" >
                                    <asp:ListItem Text="" Value=""></asp:ListItem>
                                    <asp:ListItem Text="Canceled" Value="0"></asp:ListItem>
                                    <asp:ListItem Text="On Offer" Value="1"></asp:ListItem> 
                                    <asp:ListItem Text="For Consideration" Value="2"></asp:ListItem>    
                                    <asp:ListItem Text="Make Offer" Value="3"></asp:ListItem>    
                                    <asp:ListItem Text="On Hold" Value="4"></asp:ListItem>    
                                </asp:DropDownList>  
                            </td>
                        </tr>       
                        <tr>
                            <td style="width:20%;">Assigned To</td>
                            <td>
                                <asp:DropDownList ID="AssignedTo" runat="server"
                                    DataSourceID="UserSqlDataSource" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true" >
                                    <asp:ListItem Text="" Value=""></asp:ListItem>
                                </asp:DropDownList> 
                            </td>
                        </tr>           
                        <tr>
                            <td style="width:20%;">Title</td>
                            <td>
                                <asp:TextBox ID="Title" runat="server" Text='<%# Eval("Title") %>' Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                   
                        <tr>
                            <td style="width:20%;">RespParty</td>
                            <td>
                                <asp:TextBox ID="RespParty" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>   
                        <tr>
                            <td style="width:20%;">Publisher</td>
                            <td>
                                <asp:TextBox ID="Publisher" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>   
                        <tr>
                            <td style="width:20%;">PubDate</td>
                            <td>
                                <asp:TextBox ID="PubDate" runat="server" Width="70px" ></asp:TextBox>
                                <asp:ImageButton runat="Server" ID="imgBtnPubDate" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                                <ajaxToolkit:CalendarExtender ID="PubDateCE" runat="server" TargetControlID="PubDate" PopupButtonID="imgBtnPubDate"/>                                
                                <asp:CompareValidator ID="PubDateCompareValidator" runat="server" ControlToValidate="PubDate" Display="Dynamic" ErrorMessage="Invalid PubDate!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                                <ajaxToolkit:ValidatorCalloutExtender ID="PubDateCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="PubDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                            </td>
                        </tr>   
                        <tr>
                            <td style="width:20%;">Subject</td>
                            <td>
                                <asp:TextBox ID="Subject" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>   
                         <tr>
                            <td style="width:20%;">Binding</td>
                            <td>
                                <asp:TextBox ID="Binding" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                        
                        <tr>
                            <td style="width:20%;">Page Count</td>
                            <td>
                                <asp:TextBox ID="PageCount" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="PageCountCompareValidator" runat="server" ControlToValidate="PageCount" Display="Dynamic" ErrorMessage="Page Count must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>                 
                        <tr>
                            <td style="width:20%;">US List Price</td>
                            <td>
                                <asp:TextBox ID="USListPrice" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="USListPriceCompareValidator" runat="server" ControlToValidate="USListPrice" Display="Dynamic" ErrorMessage="US List Price has invalid currency value!" Text="*" Operator="DataTypeCheck" Type="Currency" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>           
                        <tr>
                            <td style="width:20%;">Demand</td>
                            <td>
                                <asp:TextBox ID="Demand" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="DemandCompareValidator" runat="server" ControlToValidate="Demand" Display="Dynamic" ErrorMessage="Demand must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>                    
                        <tr>
                            <td style="width:20%;">On Order</td>
                            <td>
                                <asp:TextBox ID="OnOrder" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="OnOrderCompareValidator" runat="server" ControlToValidate="OnOrder" Display="Dynamic" ErrorMessage="On Order must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>           
                        <tr>
                            <td style="width:20%;">On Backorder</td>
                            <td>
                                <asp:TextBox ID="OnBackorder" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="OnBackorderCompareValidator" runat="server" ControlToValidate="OnBackorder" Display="Dynamic" ErrorMessage="On Backorder must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>                 
                         <tr>
                            <td style="width:20%;">SpeedStock</td>
                            <td>
                                <asp:CheckBox ID="SpeedStock" runat="server" />
                            </td>
                        </tr>           
                         <tr>
                            <td style="width:20%;">Status</td>
                            <td>
                                <asp:TextBox ID="Status" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                  
                        <tr>
                            <td style="width:20%;">BTKey</td>
                            <td>
                                <asp:TextBox ID="BTKey" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="BTKeyCompareValidator" runat="server" ControlToValidate="BTKey" Display="Dynamic" ErrorMessage="BTKey must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>            
                        <tr>
                            <td style="width:20%;">First Printing</td>
                            <td>
                                <asp:TextBox ID="FirstPrinting" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="FirstPrintingCompareValidator" runat="server" ControlToValidate="FirstPrinting" Display="Dynamic" ErrorMessage="FirstPrinting must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>                 
                         <tr>
                            <td style="width:20%;">Ingram</td>
                            <td>
                                <asp:TextBox ID="Ingram" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>            
                         <tr>
                            <td style="width:20%;">Licensor</td>
                            <td>
                                <asp:TextBox ID="Licensor" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                   
                        <tr>
                            <td style="width:20%;">Last Date</td>
                            <td>
                                <asp:TextBox ID="LastDate" runat="server" Width="70px" ></asp:TextBox>
                                <asp:ImageButton runat="Server" ID="imgBtnLastDate" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                                <ajaxToolkit:CalendarExtender ID="LastDateCE" runat="server" TargetControlID="LastDate" PopupButtonID="imgBtnLastDate"/>                                
                                <asp:CompareValidator ID="LastDateCompareValidator" runat="server" ControlToValidate="LastDate" Display="Dynamic" ErrorMessage="Invalid Last Date!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                                <ajaxToolkit:ValidatorCalloutExtender ID="LastDateCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="LastDateCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                            </td>
                        </tr>                  
                         <tr>
                            <td style="width:20%;">Comments</td>
                            <td>
                                <asp:TextBox ID="Comments" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>          
                         <tr>
                            <td style="width:20%;">Instructions</td>
                            <td>
                                <asp:TextBox ID="Note" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                   
                        <tr>
                            <td style="width:20%;">First Appearance</td>
                            <td>
                                <asp:TextBox ID="FirstAppearance" runat="server" Width="70px" ></asp:TextBox>
                                <asp:ImageButton runat="Server" ID="imgBtnFirstAppearance" ImageUrl="~/Images/Calendar_scheduleHS.png" AlternateText="Click here to display calendar" />
                                <ajaxToolkit:CalendarExtender ID="FirstAppearanceCE" runat="server" TargetControlID="FirstAppearance" PopupButtonID="imgBtnFirstAppearance"/>                                
                                <asp:CompareValidator ID="FirstAppearanceCompareValidator" runat="server" ControlToValidate="FirstAppearance" Display="Dynamic" ErrorMessage="Invalid First Appearance!" Text="*" Operator="DataTypeCheck" Type="Date" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                                <ajaxToolkit:ValidatorCalloutExtender ID="FirstAppearanceCompareValidator_ValidatorCalloutExtender" runat="server" Enabled="True" TargetControlID="FirstAppearanceCompareValidator"></ajaxToolkit:ValidatorCalloutExtender>
                            </td>
                        </tr>           
                         <tr>
                            <td style="width:20%;">Material</td>
                            <td>
                                <asp:TextBox ID="Material" runat="server" Width="80%" ></asp:TextBox>
                            </td>
                        </tr>                
                        <tr>
                            <td style="width:20%;">Unit Sales</td>
                            <td>
                                <asp:TextBox ID="UnitSales" runat="server" Width="80%" ></asp:TextBox>
                                <asp:CompareValidator ID="UnitSalesCompareValidator" runat="server" ControlToValidate="UnitSales" Display="Dynamic" ErrorMessage="Unit Sales must be an integer!" Text="*" Operator="DataTypeCheck" Type="Integer" ValidationGroup="licensing_validation" ></asp:CompareValidator>
                            </td>
                        </tr>                 
                    </table>   
                </div>
            
                <div align="center">  
                <asp:TextBox ID="txtLDError" runat="server" BackColor="Transparent" 
                    BorderStyle="None" CssClass="Warning" Text="Set Dynamically" 
                    TextMode="MultiLine" Visible="False" Width="500px"></asp:TextBox>
                <br />
                <asp:Button ID="btnLicensingDetailSubmit" runat="server" 
                    OnClick="btnLicensingDetailSubmit_Click" Text="Submit" ValidationGroup="licensing_validation" />
                <asp:Button ID="btnLicensingDetailCancel" runat="server" Text="Cancel" />
            </div> 
            </ContentTemplate>     
        </asp:Panel> 
    
    <asp:Label ID="Label1" runat="server" Text="Show rows:" />
    <asp:DropDownList ID="ddlPageSize" runat="server" AutoPostBack="true" 
        OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged">
        <asp:ListItem Value="20" />
        <asp:ListItem Value="50" />
        <asp:ListItem Value="100" Selected="True" />
    </asp:DropDownList>
    &nbsp;
    Page 
    <asp:TextBox ID="txtGoToPage" runat="server" AutoPostBack="true" 
        OnTextChanged="GoToPage_TextChanged" CssClass="gotopage" />
    of
    <asp:Label ID="lblTotalNumberOfPages" runat="server" />
    &nbsp;
    <asp:Button ID="btnPrev" runat="server" CommandName="Page" Enabled="false" 
        ToolTip="Previous Page" CssClass="previous" OnClick="btnPrev_Click" />
    <asp:Button ID="btnNext" runat="server" CommandName="Page" ToolTip="Next Page" 
        CssClass="next" OnClick="btnNext_Click" />     

    <br />
    <br />    
    <asp:Button ID="btnExport" runat="server" Text="Export to Excel" 
        onclick="btnExport_ExportToExcel" />
    <asp:Button ID="btnImport" runat="server" Text="Import from Excel" onclick="btnImport_Click" />
    <br />
    <br />
         
    <asp:Button ID="btnLicenseBook" runat="server" Text="License" 
        Width="100px" onclick="btnLicenseBook_Click" />          
    <asp:Button ID="btnSubmitOffer" runat="server" Text="Submit Offer" 
        Width="100px" onclick="btnSubmitOffer_Click" />  
    <asp:Button ID="btnToConsider" runat="server" Height="26px" Text="To Consider" OnClick="btnToConsider_Click" 
        Width="100px" />    
    <asp:Button ID="btnMakeOffer" runat="server" Text="Make Offer"
        Width="100px" onclick="btnMakeOffer_Click" />  
    <asp:Button ID="btnPutOnHold" runat="server" Text="Put On Hold" Width="100px" 
        onclick="btnPutOnHold_Click" />
    <asp:Button ID="btnAssignTitle" runat="server" Text="Assign Title" Width="100px" onclick="btnAssignTitle_Click" />
    <asp:Button ID="btnCancel" runat="server" Text="Cancel" Width="100px"  onclick="btnCancel_Click" />
    
    <asp:Button ID="btnShowSubmitOfferPopup" runat="server" style="display:none" />
    <asp:Button ID="btnShowCancelPopup" runat="server" style="display:none" />
    <asp:Button ID="btnShowAssignTitlePopup" runat="server" style="display:none" />
    <asp:Button ID="btnShowPutOnHoldPopup" runat="server" style="display:none" />
    <asp:Button ID="btnShowImportPopup" runat="server" style="display:none" />            
    <asp:Button ID="btnShowOrderByPopup" runat="server" style="display:none" />            
    <asp:Button ID="btnShowHideColumnsPopup" runat="server" style="display:none" /> 
    <asp:Button ID="btnShowFilterByLicensorsPopup" runat="server" style="display:none" />                   
    <asp:Button ID="btnShowCustomViewsPopup" runat="server" style="display:none" />   

Licensing.ascs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Data;
using System.Web.UI.HtmlControls;
using Yogesh.ExcelXml;
using System.Drawing;
using System.Text;
using System.Data.Odbc;
using System.Web.Configuration;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Web.UI.WebControls.WebParts;
using System.Web.Services;
using AjaxControlToolkit;

class Offer
{
    public Offer(string ean, DateTime date, double amount)
    {
        this.EAN = ean;
        this.Date = date;
        this.Amount = amount;
    }
    public string EAN { get; set; }
    public DateTime Date { get; set; }
    public double Amount { get; set; }
}

class LicensedBook
{
    public LicensedBook(string title, string respParty, DateTime pubDate, string publisherLicensor, int firstPrint)
    {
        this.Title = title;
        this.RespParty = respParty;
        this.PubDate = pubDate;
        this.PublisherLicensor = publisherLicensor;
        this.FirstPrint = firstPrint;
    }
    public string Title { get; set; }
    public string RespParty { get; set; }
    public DateTime PubDate { get; set; }
    public string PublisherLicensor { get; set; }
    public int FirstPrint { get; set; }
}

class CustomView
{
    public CustomView(string filterField, string filterValue, string orderBy, string hiddenFields, string licensorsToFilterBy, bool bIsPrivate)
    {
        this.FilterField = filterField;
        this.FilterValue = filterValue;
        this.OrderBy = orderBy;
        this.HiddenFields = hiddenFields;
        this.LicensorsToFilterBy = licensorsToFilterBy;
        this.IsPrivate = bIsPrivate;
    }
    public string FilterField { get; set; }
    public string FilterValue { get; set; }
    public string OrderBy { get; set; }
    public string HiddenFields { get; set; }
    public string LicensorsToFilterBy { get; set; }
    public bool   IsPrivate { get; set; }
}

public partial class Licensing : BaseUserControl
{
    #region Data Members

    protected static Dictionary<string, string> dbColumns = new Dictionary<string, string>() { /*{ "Color", "Int32" },*/ { "EAN", "String" }, { "TantorStatus", "Int32" }, { "AssignedTo", "String" }, { "Title", "String" }, { "RespParty", "String" }, { "Publisher", "String" }, { "PubDate", "DateTime" }, { "Subject", "String" }, { "Binding", "String" }, { "PageCount", "Int32" }, { "USListPrice", "Decimal" }, { "Demand", "Int32" }, { "OnOrder", "Int32" }, { "OnBackorder", "Int32" }, { "SpeedStock", "Boolean" }, { "Status", "String" }, { "BTKey", "Int32" }, { "FirstPrinting", "Int32" }, { "Ingram", "String" }, { "Licensor", "String" }, { "OfferDate", "DateTime" }, { "OfferAmount", "Decimal" }, { "LastDate", "DateTime" }, { "Comments", "String" }, { "Note", "String" }, { "FirstAppearance", "DateTime" }, { "Material", "String" }, { "UnitSales", "Int32" } };
    protected static string selectAllBookQuest =
            @"SELECT b.Color, b.TantorStatus TantorStatusNumber, b.AssignedTo AssignedToNumber, b.EAN,
            CASE TantorStatus WHEN NULL THEN '' WHEN 0 THEN 'Canceled' WHEN 1 THEN 'On Offer' WHEN 2 THEN 'For Consideration' WHEN 3 THEN 'Make Offer' WHEN 4 THEN 'On Hold' END AS TantorStatus,
            u.Name AssignedTo, b.Title, b.RespParty, b.Publisher, b.PubDate, b.Subject, b.Binding, b.PageCount, b.USListPrice, b.Demand, b.OnOrder, b.OnBackorder, b.SpeedStock, b.Status, b.BTKey,
            b.FirstPrinting, b.Ingram, b.Licensor, bo.OfferDate, bo.Amount AS OfferAmount,
            b.LastDate, b.Comments, b.Note, b.FirstAppearance, b.Material, b.UnitSales
            From BookQuest b ";
    protected static Dictionary<Int32, string> cancelReasons = new Dictionary<Int32, string>() { { 0, "Outbid" }, { 1, "Not Available" }, { 2, "Withdrawn" } };
    protected enum FILTERING_CRITERIA { ALL = -2, MY_TITLES = -1, CANCELLED = 0, ON_OFFER = 1, FOR_CONSIDERATION = 2, MAKE_OFFER = 3, ON_HOLD = 4, EXISTING_AUTHORS = 5, CUSTOM_VIEW = 6 }
    protected enum SOME_COLUMNS { COLOR = 0, CHECKBOX_SELECTOR = 1, LINK_BUTTON = 2, FIRST_DATA_COLUMN = 3, PUB_DATE = 9, OFFER_AMOUNT = 24 };

    protected const int FIRST_CUSTOMVIEWS_INDEX = 9;
    /*
        ddlFilter's items before FIRST_CUSTOMVIEWS_INDEX:
            0 - "All"
            1 - "My Titles"
            2 - "Cancelled Titles"
            3 - "On Offer"
            4 - "For Consideration"
            5 - "Make Offer"
            6 - "On Hold"
            7 - "Titles from Existing Authors"
            8 - "***"
     */

    private const int _firstEditCellIndex = 3;  // 0 is Color, 1 is CheckBox, 2 is SingleClick
    private const int _firstEditHeaderColumnIndex = 1;  // 0 is CheckBox

    protected static string[] excelRawColumns = { "ISBN", "Title", "Resp Party", "Publisher", "Pub Date", "Subject", "Binding", "Page Count", "US List Price", "Demand", "On Order", "On Backorder", "Speedstock", "Status", "BT Key", "1st Printing" };
    protected static string[,] dbRawColumns = { { "EAN", "String" }, { "Title", "String" }, { "RespParty", "String" }, { "Publisher", "String" }, { "PubDate", "DateTime" }, { "Subject", "String" }, { "Binding", "String" }, { "PageCount", "Int32" }, { "USListPrice", "Decimal" }, { "Demand", "Int32" }, { "OnOrder", "Int32" }, { "OnBackorder", "Int32" }, { "SpeedStock", "Boolean" }, { "Status", "String" }, { "BTKey", "Int32" } };
    protected const int MAX_RECORDS_INSERTED_AT_ONCE = 1000;

    string FileToImport;

    private string _hiddenColumns = null;
    protected string HiddenColumns
    {
        get
        {
            if (_hiddenColumns == null)
            {
                _hiddenColumns = Request.Cookies["HiddenColumns"] == null ? "" : Request.Cookies["HiddenColumns"].Value;
            }
            return _hiddenColumns;
        }
        set
        {
            if (string.IsNullOrEmpty(value) && Request.Cookies["HiddenColumns"] != null)
            {
                Response.Cookies["HiddenColumns"].Expires = DateTime.Now.AddDays(-1);
            }
            else if(!string.IsNullOrEmpty(value))
            {
                Response.Cookies["HiddenColumns"].Value = value;
                Response.Cookies["HiddenColumns"].Expires = DateTime.Now.AddDays(365);
            }
            _hiddenColumns = value;
        }
    }
    private string CustomViewName = null;

    #endregion

    #region Events Handlers

    protected void Page_Load(object sender, EventArgs e)
    {
        int selectedIndex = ddlBookQuestFields.SelectedIndex;

        string[] columns = new string[dbColumns.Count + 1]; // + 1 because we need one entry for *None
        columns = dbColumns.Keys.ToArray();
        columns[dbColumns.Count - 1] = "*None";

        Array.Sort(columns);
        ddlBookQuestFields.DataSource = columns;
        ddlBookQuestFields.DataBind();

        ddlBookQuestFields.SelectedIndex = selectedIndex;

        if (!IsPostBack)
        {
            UpdateDDLFilterWithCustomViews();
        }
        else
        {
            Page.Validate("filter");
            if (!IsValid)
                return;
        }

        HideFields();

        if (!IsPostBack)
        {
            string msg = Request.QueryString["success_msg"];
            if (msg != null)
                SetSuccessLabel(Request.QueryString["success_msg"]);
        }
        Session["LicensingPageCount"] = GetPageCount();

        RememberOldValues();

        Filter();
        
        RePopulateValues();
    }

    #region navigation
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList dropDown = (DropDownList)sender;

        FrontListGridView.PageSize = int.Parse(dropDown.SelectedValue);
        Session["LicensingPageCount"] = GetPageCount();
        Filter();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GoToPage_TextChanged(object sender, EventArgs e)
    {
        RememberOldValues();

        var txtGoToPage = (System.Web.UI.WebControls.TextBox)sender;

        if (Session["LicensingSavedPage"] != null)
            txtGoToPage.Text = Session["LicensingSavedPage"] as string;

        int pageNumber;
        if (int.TryParse(txtGoToPage.Text.Trim(), out pageNumber) && pageNumber > 0 && pageNumber <= (int)Session["LicensingPageCount"])
        {
            Session["LicensingPageIndex"] = pageNumber - 1;
        }
        else
        {
            Session["LicensingPageIndex"] = 0;
        }
        Filter();
        RePopulateValues();
        EnableDisableNavigation();
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        RememberOldValues();

        int LicensingPageIndex = (Session["LicensingPageIndex"] == null) ? 0 : (int)Session["LicensingPageIndex"];
        Session["LicensingPageIndex"] = ++LicensingPageIndex;

        Filter();
        RePopulateValues();
        EnableDisableNavigation();
    }

    protected void btnPrev_Click(object sender, EventArgs e)
    {
        RememberOldValues();

        int LicensingPageIndex = (Session["LicensingPageIndex"] == null) ? 0 : (int)Session["LicensingPageIndex"];
        Session["LicensingPageIndex"] = --LicensingPageIndex;

        Filter();
        RePopulateValues();
        EnableDisableNavigation();
    }

    #endregion

    protected void btnFilter_OnClick(object sender, EventArgs e)
    {
        if (IsValid)
        {
            Session["LicensingPageCount"] = GetPageCount();
            Session["LicensingPageIndex"] = 0;   // we want to go the the 1st page if filter criteria changed

            if (ddlFilter.SelectedIndex >= FIRST_CUSTOMVIEWS_INDEX && Session["CustomViews"] != null)
            {
                var customViews = Session["CustomViews"] as Dictionary<string, CustomView>;
                var customView = customViews[ddlFilter.SelectedValue];

                CustomViewName = ddlFilter.SelectedValue;

                Session["OrderBy"] = customView.OrderBy;
                Session["LicensorsToFilterBy"] = customView.LicensorsToFilterBy;

                HiddenColumns = customView.HiddenFields;

                HideFields();

                ddlBookQuestFields.SelectedValue = customView.FilterField;
                txtFilterValue.Text = customView.FilterValue;

            }
            else
            {
                Session["LicensorsToFilterBy"] = null;
                Session["OrderBy"] = null;
            }

            // Reset selected indices:
            FrontListGridView.SelectedIndex = FrontListGridView.EditIndex = -1;

            EnableDisableNavigation();

            Filter();  
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void FrontListGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gridView = (GridView)sender;

        try
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[(int)SOME_COLUMNS.COLOR].Visible = false;// we could not make the Color column invisible in .aspx because we need its content to set our row color below

                if (Session["OrderBy"] != null && (Session["OrderBy"]).ToString() != string.Empty)
                {
                    string strOrderBy = (Session["OrderBy"]).ToString();
                    string[] orderBy = strOrderBy.Split(',');

                    foreach (TableCell cell in e.Row.Cells)
                    {
                        foreach (string criterion in orderBy)
                        {
                            if (cell.Text.Replace(" ", "") == criterion)
                            {
                                cell.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Yellow");
                                break;
                            }
                        }
                    }
                }
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int iColor;
                if (Int32.TryParse((e.Row.Cells[(int)SOME_COLUMNS.COLOR].Controls[1] as Label).Text, out iColor))
                    e.Row.BackColor = System.Drawing.ColorTranslator.FromOle(iColor);
                e.Row.Cells[(int)SOME_COLUMNS.COLOR].Visible = false; // we could not make it invisible in .aspx before we set our row color above

                // Get the LinkButton control in the third cell
                LinkButton _singleClickButton = (LinkButton)e.Row.Cells[(int)SOME_COLUMNS.LINK_BUTTON].Controls[0];
                // Get the javascript which is assigned to this LinkButton
                string _jsSingle = Page.ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");

                for (int cellCount = (int)SOME_COLUMNS.FIRST_DATA_COLUMN; cellCount < e.Row.Cells.Count; cellCount++) // start from FIRST_DATA_COLUMN because we don't want fire click event on the Color field or checkbox 
                {
                    e.Row.Cells[cellCount].Attributes["onclick"] = _jsSingle;
                    e.Row.Cells[cellCount].Attributes["style"] = "cursor:pointer;cursor:hand;";
                }
            }
        }
        catch (Exception ex)
        {
            SetWarningLabel(ex.Message);
            return;
        }
    }

    protected void FrontListGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridView _gridView = (GridView)sender;

        switch (e.CommandName)
        {
            case ("Select"):
                // Get the row index
                int _rowIndex = int.Parse(e.CommandArgument.ToString());

                ShowLicensingDetail(_rowIndex);
                break;
        }
    }

    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        ShowLicensingDetail(-1);
    }

    protected void ValidateCustomViews(object sender, ServerValidateEventArgs e)
    {
        ValidateDataType(ddlCVBookQuestFields.SelectedValue,
            ddlCVBookQuestFields.SelectedValue == "*None" || string.IsNullOrEmpty(ddlCVBookQuestFields.SelectedValue) ? "" : dbColumns[ddlCVBookQuestFields.SelectedValue], 
            e, sender as CustomValidator);
    }

    protected void Custom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        ValidateDataType(ddlBookQuestFields.SelectedValue,
            ddlBookQuestFields.SelectedValue == "*None" || string.IsNullOrEmpty(ddlBookQuestFields.SelectedValue) ? "" : dbColumns[ddlBookQuestFields.SelectedValue], 
            e, sender as CustomValidator);
    }

    protected void btnExport_ExportToExcel(object sender, EventArgs e)
    {
        if (Session["LicensingSelect"] == null)
        {
            SetWarningLabel("Your session expired. Please refresh the page and try to export again.");
            return;
        }
        object result = DBOperations.Execute(false, CommandType.Text, null, Session["LicensingSelect"].ToString(), null);

        if (result is string)    // an error message was returned
        {
            SetWarningLabel("Export failed: Could not retrieve data: <br>" + result.ToString());
            return;
        }
        if (result is OdbcDataReader)
        {
            OdbcDataReader odbcReader = result as OdbcDataReader;
            DataTable table = new DataTable();
            DataReaderAdapter dar = new DataReaderAdapter();
            dar.FillFromReader(table, odbcReader);

            ExcelXmlWorkbook book = new ExcelXmlWorkbook();

            Worksheet sheet = book[0];

            // Export column names
            int tableColumnIndex;
            int sheetColumnIndex = 0;
            for (tableColumnIndex = 3; tableColumnIndex < table.Columns.Count; tableColumnIndex++, sheetColumnIndex++)   // tableColumnIndex 0 is for color, 1 for TantorStatusNumber, 2 for AssignedToNumber that we don't want to display, so we start from 3
            {
                sheet[sheetColumnIndex, 0].Value = table.Columns[tableColumnIndex].ToString();
            }
            // Column names for calculated fields (that are not from the database directly)
            #region Calculated Fields Headers
            // sheet[column, row]
            sheet[sheetColumnIndex++, 0].Value = "Author cd total";
            sheet[sheetColumnIndex++, 0].Value = "Author pap total";
            sheet[sheetColumnIndex++, 0].Value = "Author hc total";
            sheet[sheetColumnIndex++, 0].Value = "Author aud total";
            sheet[sheetColumnIndex++, 0].Value = "Combined";
            sheet[sheetColumnIndex++, 0].Value = "*bl";
            sheet[sheetColumnIndex++, 0].Value = "*kk";
            sheet[sheetColumnIndex++, 0].Value = "*lj";
            sheet[sheetColumnIndex++, 0].Value = "*pw";
            sheet[sheetColumnIndex++, 0].Value = "nyte";
            sheet[sheetColumnIndex++, 0].Value = "nytn";
            sheet[sheetColumnIndex++, 0].Value = "nytb";
            sheet[sheetColumnIndex++, 0].Value = "sum";
            sheet[sheetColumnIndex++, 0].Value = "Main cat";
            sheet[sheetColumnIndex++, 0].Value = "Alt Combi FP";
            #endregion

            // Export data

            int sheetRowIndex = 1;  // 0 is column names row, so we start here from 1
            foreach (DataRow dr in table.Rows)
            {
                for (tableColumnIndex = 3, sheetColumnIndex = 0; tableColumnIndex < table.Columns.Count; tableColumnIndex++, sheetColumnIndex++)   // tableColumnIndex 0 is for color, 1 for TantorStatusNumber, 2 for AssignedToNumber that we don't want to display, so we start from 3
                {
                    sheet[sheetColumnIndex, sheetRowIndex].Value = dr[tableColumnIndex].ToString();
                }

                if (dr[0] != DBNull.Value)  // Check for the color stored in the first column
                {
                    Range range = new Range(sheet[0, sheetRowIndex], sheet[table.Columns.Count, sheetRowIndex]);
                    range.Interior.Color = ColorTranslator.FromOle(Convert.ToInt32(dr[0]));         // dr[0] because Color goes first in the row
                }
                sheetRowIndex++;
            }

            string absolutePath = @"C:/Inetpub/wwwroot";
            string relativePath = @"/TPS/Temp/" + System.DateTime.Now.Ticks.ToString() + "_Frontlist.xls";

            if (book.Export(absolutePath + relativePath))
            {
                SetSuccessLabel("The export succeeded. Please <A href='" + relativePath + "'> download</A> your file.");
            }
            else
            {
                SetWarningLabel("Unspecified error occured. The export failed.");
            }
        }
    }

    protected void btnLicenseBook_Click(object sender, EventArgs e)
    {
        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }

        // Retrieve information of the users that should receive email notification
        var emails = new List<string>();
        string emailText = string.Empty;

        string commandText = @"SELECT u.Email, s.EmailTemplate
                               FROM TPSSettingUserEmailLink sul 
                               JOIN TPSSetting s ON sul.TPSSettingID = s.ID 
                               JOIN TPSSection sc ON s.TPSSectionID = sc.ID
                               JOIN User u ON sul.UserID = u.ID
                               WHERE sc.ID = " + (int)Collections.TPS_SECTIONS.LICENSING + " AND s.SendEmailAlert = 1;";

        object result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);
        if (result is string)    // an error message was returned
        {
            SetWarningLabel("Failed to retrieve Email information: <br />" + result.ToString());
        }
        else if (result is OdbcDataReader)
        {
            OdbcDataReader odbcReader = result as OdbcDataReader;
            while (odbcReader.Read())
            {
                emails.Add(odbcReader["Email"].ToString());
                if (emailText == string.Empty)
                {
                    emailText = odbcReader["EmailTemplate"].ToString();
                }
            }
        }

        var licensedBooks = new Dictionary<string, LicensedBook>();

        // Get each book information for email notification
        StringBuilder EANsIN = new StringBuilder("(");
        foreach (string _ean in keys.Keys)
        {
            EANsIN.Append(_ean + ",");
        }
        EANsIN = EANsIN.Replace(',', ')', EANsIN.Length - 1, 1);

        commandText = @"SELECT b.EAN, b.Title, b.RespParty, b.PubDate, CONCAT(b.Publisher, '/', b.Licensor) AS PublisherLicensor, FirstPrinting
                                FROM BookQuest b
                                WHERE EAN IN " + EANsIN.ToString();

        result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);
        if (result is string)    // an error message was returned
        {
            SetWarningLabel("Failed to retrieve Email information: <br />" + result.ToString());
        }
        else if (result is OdbcDataReader)
        {
            OdbcDataReader odbcReader = result as OdbcDataReader;
            while (odbcReader.Read())
            {
                licensedBooks[odbcReader["EAN"].ToString()] = new LicensedBook(
                    odbcReader["Title"].ToString(),
                    odbcReader["RespParty"].ToString(),
                    odbcReader["PubDate"] == DBNull.Value ? DateTime.MinValue : (DateTime)odbcReader["PubDate"],
                    odbcReader["PublisherLicensor"].ToString(),
                    odbcReader["FirstPrinting"] == DBNull.Value ? 0 : Convert.ToInt32(odbcReader["FirstPrinting"]));
            }
        }

        // License Books
        commandText = "{ CALL LicenseBook(?) }";

        string FailedLicenseEAN = string.Empty;
        string SuccessfulEAN = string.Empty;

        foreach (string _ean in keys.Keys)
        {
            var parameters = new[] {
            new OdbcParameter("pEAN", _ean) };

            result = DBOperations.Execute(true, CommandType.StoredProcedure, null, commandText, parameters);

            if (result is string)    // an error message was returned
            {
                FailedLicenseEAN += _ean + ": " + result + "<br />";
            }
            else
            {
                SuccessfulEAN += _ean + ", ";
                // Send an Email notification
                foreach (string email in emails)
                {
                    if (email == string.Empty)
                    {
                        continue;
                    }
                    string emailResult = EmailHandler.Emailer.SendMessage(email, "tps@tantor.com",
                            "New Title: " + licensedBooks[_ean].Title,
                             string.Format(emailText, _ean, licensedBooks[_ean].Title, licensedBooks[_ean].RespParty,
                             licensedBooks[_ean].PubDate == DateTime.MinValue ? "" : licensedBooks[_ean].PubDate.ToShortDateString(), 
                             licensedBooks[_ean].PublisherLicensor, licensedBooks[_ean].FirstPrint));
                }
                
            }
        }
        if (SuccessfulEAN != string.Empty)
        {
            SuccessfulEAN = SuccessfulEAN.TrimEnd(' ', ',');
            if (Session["CHECKED_ITEMS"] != null)
            {
                string[] EANsRemoved = SuccessfulEAN.Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries);
                Dictionary<string, Offer> checkedItems = (Dictionary<string, Offer>)Session["CHECKED_ITEMS"];
                foreach (string _ean in EANsRemoved)
                {
                    checkedItems.Remove(_ean);
                }
                Session["CHECKED_ITEMS"] = checkedItems;
            }

            SetSuccessLabel("The following books were successfully licensed: <br />" +
                SuccessfulEAN.TrimEnd(' ', ','));

            Filter();
        }
        if (FailedLicenseEAN != string.Empty)
        {
            SetWarningLabel("Failed to license the following book(s): <br />" + FailedLicenseEAN);
        }
        LicensingDetailModalPopupExtender.Hide();
    }


    protected void btnSubmitOffer_Click(object sender, EventArgs e)
    {
        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }

        DataTable submitOfferTable = new DataTable();
        DataColumn columnEAN = new DataColumn("EAN", Type.GetType("System.String"));
        columnEAN.Unique = true;
        submitOfferTable.Columns.Add(columnEAN);
        DataColumn columnOfferDate = new DataColumn("OfferDate", Type.GetType("System.DateTime"));
        submitOfferTable.Columns.Add(columnOfferDate);
        DataColumn columnAmount = new DataColumn("Amount", Type.GetType("System.Double"));
        submitOfferTable.Columns.Add(columnAmount);
        DataColumn columnExpirationDate = new DataColumn("ExpirationDate", Type.GetType("System.DateTime"));
        submitOfferTable.Columns.Add(columnExpirationDate);

        foreach (string EAN in keys.Keys)
        {
            DataRow submitOfferRow = submitOfferTable.NewRow();
            submitOfferRow["EAN"] = EAN;
            submitOfferRow["OfferDate"] = DateTime.Now;
            submitOfferRow["Amount"] = keys[EAN].Amount;
            submitOfferRow["ExpirationDate"] = (keys[EAN].Date == DateTime.MinValue) ? DateTime.MinValue : keys[EAN].Date.AddDays(63);   // by default, expiration date is PubDate + 9 weeks

            submitOfferTable.Rows.Add(submitOfferRow);
        }

        SubmitOfferGridView.DataSource = submitOfferTable;
        SubmitOfferGridView.DataBind();

        SubmitOfferModalPopupExtender.Show();
    }

    protected void btnToConsider_Click(object sender, EventArgs e)
    {
        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }

        StringBuilder commandText = new StringBuilder("UPDATE BookQuest SET TantorStatus = 2, Color = " + ColorTranslator.ToOle(Color.Yellow) +
                             " WHERE EAN IN(", 500);
        foreach (string EAN in keys.Keys)
        {
            commandText.Append("'" + EAN + "',");
        }
        // replace the last comma with a closing bracket
        commandText = commandText.Replace(',', ')', commandText.Length - 1, 1);

        object result = DBOperations.Execute(true, CommandType.Text, null, commandText.ToString(), null);
        int recordsUpdated = 0;
        if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
        {
            SetWarningLabel("Failed to update Tantor Status: <br>" + result.ToString());
        }
        else
            Filter();
    }

    protected void btnMakeOffer_Click(object sender, EventArgs e)
    {
        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }

        StringBuilder commandText = new StringBuilder("UPDATE BookQuest SET TantorStatus = 3, Color = " + ColorTranslator.ToOle(Color.Orange) +
                             " WHERE EAN IN(", 500);
        foreach (string EAN in keys.Keys)
        {
            commandText.Append("'" + EAN + "',");
        }
        // replace the last comma with a closing bracket
        commandText = commandText.Replace(',', ')', commandText.Length - 1, 1);

        object result = DBOperations.Execute(true, CommandType.Text, null, commandText.ToString(), null);
        int recordsUpdated = 0;
        if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
        {
            SetWarningLabel("Failed to update Tantor Status: <br>" + result.ToString());
        }
        else
            Filter();
    }

    protected void btnPutOnHold_Click(object sender, EventArgs e)
    {
        // This method is used only to check if any records were checked (selected)

        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }
        txtOnHoldComment.Text = string.Empty;
        OnHoldModalPopupExtender.Show();
    }

    protected void btnAssignTitle_Click(object sender, EventArgs e)
    {
        // This method is used only to check if any records were checked (selected)

        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }
        AssignTitleModalPopupExtender.Show();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        RememberOldValues();    // Store in Session keys of the checked rows on the current page

        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
        {
            SetWarningLabel("You did not select any records.");
            return;
        }

        DataTable cancelTable = new DataTable();
        DataColumn columnEAN = new DataColumn("EAN", Type.GetType("System.String"));
        columnEAN.Unique = true;
        cancelTable.Columns.Add(columnEAN);
        DataColumn columnReason = new DataColumn("Reason", Type.GetType("System.String"));
        cancelTable.Columns.Add(columnReason);
        DataColumn columnComments = new DataColumn("Comments", Type.GetType("System.String"));
        cancelTable.Columns.Add(columnComments);

        foreach (string EAN in keys.Keys)
        {
            DataRow cancelRow = cancelTable.NewRow();
            cancelRow["EAN"] = EAN;

            cancelTable.Rows.Add(cancelRow);
        }

        CancelGridView.DataSource = cancelTable;
        CancelGridView.DataBind();

        CancelModalPopupExtender.Show();
    }

    protected void btnImport_Click(object sender, EventArgs e)
    {
        txtError.Text = string.Empty;
        for (int index = 0; index < chlstPublishers.Items.Count; index++)
        {
            chlstPublishers.Items[index].Selected = false;
        }

        string commandText = @"SELECT ID FROM Publisher WHERE Import = 1;";

        object result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);
        if (result is string)    // an error message was returned
        {
            txtError.Text = "Failed to retrieve information on publishers whose books are to be imported: \n" + result.ToString();
            txtError.Visible = true;
        }
        else if (result is OdbcDataReader)
        {
            OdbcDataReader odbcReader = result as OdbcDataReader;
            while (odbcReader.Read())
            {
                ListItem currentCheckBox = chlstPublishers.Items.FindByValue(odbcReader["ID"].ToString());
                if (currentCheckBox != null)
                {
                    currentCheckBox.Selected = true;
                }
            }
        }


        ImportModalPopupExtender.Show();
    }

    protected void btnSetSort_Click(object sender, EventArgs e)
    {
        List<string> sourceFields = new List<string>(dbColumns.Count);
        foreach(string field in dbColumns.Keys)
            sourceFields.Add(field);

        if (Session["OrderBy"] != null && (Session["OrderBy"]).ToString() != string.Empty)
        {
            string strOrderBy = Session["OrderBy"] as string;

            SelectedItems.Value = strOrderBy + ",";

            string[] orderBy = strOrderBy.Split(',');

            lstSelectedFields.DataSource = orderBy;
            lstSelectedFields.DataBind();

            foreach (string selectedField in orderBy)
            {
                sourceFields.Remove(selectedField);
            }
        }
        lstSourceFields.DataSource = sourceFields;
        lstSourceFields.DataBind();

        OrderByModalPopupExtender.Show();
    }

    protected void btnHideColumns_Click(object sender, EventArgs e)
    {
        lstFields.DataSource = dbColumns.Keys;
        //lstFields.DataSource = sortFields;
        lstFields.DataBind();

        if (Request.Cookies["HiddenColumns"] != null)
        {
            string strHiddenColumns = Server.HtmlEncode(Request.Cookies["HiddenColumns"].Value);
            string[] hiddenColumns = strHiddenColumns.Split('#');
            foreach (string field in hiddenColumns)
            {
                ListItem item = lstFields.Items.FindByText(field);
                if(item != null)
                    item.Selected = true;
            }
        }
        HideColumnsModalPopupExtender.Show();
    }

    protected void btnFilterByLicensors_Click(object sender, EventArgs e)
    {
        lstLicensors.ClearSelection();
        if (Session["LicensorsToFilterBy"] != null && (Session["LicensorsToFilterBy"]).ToString() != string.Empty)
        {
            string strLicensorsToFilterBy = Session["LicensorsToFilterBy"].ToString();

            string[] licensorsToFilterBy = strLicensorsToFilterBy.Split('#');

            foreach (string licensor in licensorsToFilterBy)
            {
                ListItem foundLicensor = lstLicensors.Items.FindByValue(licensor);
                if (foundLicensor != null)
                {
                    foundLicensor.Selected = true;
                }
            }
        }
        FilterByLicensorsModalPopupExtender.Show();
    }

    protected void btnCustomViews_Click(object sender, EventArgs e)
    {
        // Fill dropdown list with fields to filter by
        string[] columns = new string[dbColumns.Count + 1]; // + 1 because we need one entry for *None
        columns = dbColumns.Keys.ToArray();
        columns[dbColumns.Count - 1] = "*None";

        Array.Sort(columns);
        ddlCVBookQuestFields.DataSource = columns;
        ddlCVBookQuestFields.DataBind();

        // Fill listbox with fields to select from to sort by
        List<string> sourceFields = new List<string>(dbColumns.Count);

        foreach (string field in dbColumns.Keys)
            sourceFields.Add(field);

        // Fill listbox with fields to select for hiding
        lstCustomViewsFields.DataSource = dbColumns.Keys;
        lstCustomViewsFields.DataBind();

        string strOrderBy = string.Empty;

        lstCustomViewsFields.ClearSelection();
        lstCustomViewsLicensors.ClearSelection();

        if (ddlFilter.SelectedIndex >= FIRST_CUSTOMVIEWS_INDEX && Session["CustomViews"] != null)
        {
            var customViews = Session["CustomViews"] as Dictionary<string, CustomView>;
            var customView = customViews[ddlFilter.SelectedValue];

            // Set Custom View Name
            txtCustomViewName.Text = ddlFilter.SelectedValue;

            // Set public or private
            rdoPrivate.Checked = customView.IsPrivate;

            // Set Filter preferences
            ddlCVBookQuestFields.SelectedValue = customView.FilterField;
            txtCVFilterValue.Text = customView.FilterValue;

            // Set Sort preferences
            strOrderBy = customView.OrderBy;

            SelectedItems.Value = strOrderBy + ",";

            string[] orderBy = strOrderBy.Split(',');

            lstCustomViewsSelectedFields.DataSource = orderBy;
            lstCustomViewsSelectedFields.DataBind();

            foreach (string selectedField in orderBy)
            {
                sourceFields.Remove(selectedField);
            }

            // Set Hide Columns preferences
            string strHiddenColumns = customView.HiddenFields;
            string[] hiddenColumns = strHiddenColumns.Split('#');
            foreach (string field in hiddenColumns)
            {
                ListItem item = lstCustomViewsFields.Items.FindByText(field);
                if (item != null)
                    item.Selected = true;
            }

            // Set Licensors to Filter By preferences
            string strLicensorsToFilterBy = customView.LicensorsToFilterBy;
            if (!string.IsNullOrEmpty(strLicensorsToFilterBy))
            {
                string[] licensorsToFilterBy = strLicensorsToFilterBy.Split('#');

                foreach (string licensor in licensorsToFilterBy)
                {
                    ListItem foundLicensor = lstCustomViewsLicensors.Items.FindByValue(licensor);
                    if (foundLicensor != null)
                    {
                        foundLicensor.Selected = true;
                    }
                }
            }
        }
        else
        {
            txtCustomViewName.Text = string.Empty;
            rdoPrivate.Checked = false;
            ddlCVBookQuestFields.SelectedIndex = 0;
            txtCVFilterValue.Text = string.Empty;
            lstCustomViewsSelectedFields.Items.Clear();
        }

        lstCustomViewsSourceFields.DataSource = sourceFields;
        lstCustomViewsSourceFields.DataBind();

        CustomViewsModalPopupExtender.Show();
    }

    #region These methods handle Submit buttons on the modal popup windows clicks

    protected void btnLicensingDetailSubmit_Click(object sender, EventArgs e)
    {
        string commandText = "{ CALL InsertUpdateLicensing(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) }";

        var parameters = new[] {
        new OdbcParameter("pEAN", FrontListGridView.SelectedIndex == -1 ?  // if we are inserting a record and not updating
            EAN.Text : FrontListGridView.DataKeys[FrontListGridView.SelectedIndex].Value.ToString()),
        new OdbcParameter("pTitle", Title.Text),
        new OdbcParameter("pRespParty", RespParty.Text),
        new OdbcParameter("pPublisher", Publisher.Text),
        new OdbcParameter("pPubDate", (PubDate.Text == string.Empty) ? (object)DBNull.Value : Convert.ToDateTime(PubDate.Text)),
        new OdbcParameter("pSubject", Subject.Text),
        new OdbcParameter("pBinding", Binding.Text),
        new OdbcParameter("pPageCount", (PageCount.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(PageCount.Text)),
        new OdbcParameter("pUSListPrice", (USListPrice.Text == string.Empty) ? (object)DBNull.Value : Convert.ToDouble(USListPrice.Text)),
        new OdbcParameter("pDemand", (Demand.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(Demand.Text)),
        new OdbcParameter("pOnOrder", (OnOrder.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(OnOrder.Text)),
        new OdbcParameter("pOnBackorder", (OnBackorder.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(OnBackorder.Text)),
        new OdbcParameter("pSpeedStock", (SpeedStock.Checked == false) ? 0 : 1),
        new OdbcParameter("pStatus", Status.Text),
        new OdbcParameter("pBTKey", (BTKey.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(BTKey.Text)),
        new OdbcParameter("pFirstPrinting", (FirstPrinting.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt64(FirstPrinting.Text)),
        new OdbcParameter("pIngram", Ingram.Text),
        new OdbcParameter("pLicensor", Licensor.Text),
        new OdbcParameter("pLastDate", (LastDate.Text == string.Empty) ? (object)DBNull.Value : Convert.ToDateTime(LastDate.Text)),
        new OdbcParameter("pComments", Comments.Text),
        new OdbcParameter("pNote", Note.Text),
        new OdbcParameter("pFirstAppearance", (FirstAppearance.Text == string.Empty) ? (object)DBNull.Value : Convert.ToDateTime(FirstAppearance.Text)),
        new OdbcParameter("pMaterial", Material.Text),
        new OdbcParameter("pTantorStatus", (TantorStatus.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(TantorStatus.Text)),
        new OdbcParameter("pAssignedTo", (AssignedTo.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(AssignedTo.Text)),
        new OdbcParameter("pUnitSales", (UnitSales.Text == string.Empty) ? (object)DBNull.Value : Convert.ToInt32(UnitSales.Text)) };

        object result = DBOperations.Execute(true, CommandType.StoredProcedure, null, commandText, parameters);

        if (result is string)    // an error message was returned
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP_UpdateLicensing", "ShowLicensingDetailErrors();", true);
            txtLDError.Text = "Failed to save information.\n" + result.ToString();
            txtLDError.Visible = true;
        }
        else
        {
            Filter();
            LicensingDetailModalPopupExtender.Hide();
            SetSuccessLabel("Information was successfully saved.");
        }
    }

    protected void btnSubmitSubmitOffer_Click(object sender, EventArgs e)
    {
        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
            return;

        string commandText;
        string FailedUpdatesEAN = string.Empty;
        string FailedInsertsEAN = string.Empty;

        foreach (GridViewRow row in SubmitOfferGridView.Rows)
        {
            // First update the BookQuest table setting TantorStatus for selected records to 1 (On Offer)
            commandText =
                "UPDATE BookQuest SET TantorStatus = 1, Color = " + ColorTranslator.ToOle(Color.LightBlue) +
                " WHERE EAN = '" + row.Cells[0].Text + "';";

            object result = DBOperations.Execute(true, CommandType.Text, null, commandText, null);
            int recordsUpdated = 0;
            if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
            {
                FailedUpdatesEAN += ((FailedUpdatesEAN == string.Empty) ? "" : ", ") + row.Cells[0].Text;
                continue;
            }

            // Now insert Offer Details into the BookQuest_Offer table
            commandText =
                "INSERT INTO BookQuest_Offer (OfferDate, Amount, ExpirationDate, BookQuestID) VALUES('" +
                Convert.ToDateTime(((TextBox)row.FindControl("OfferDate")).Text).ToString("yyyy:MM:dd hh:mm:ss") + "'," +
                Convert.ToDouble(((TextBox)row.FindControl("Amount")).Text) + ",'" +
                Convert.ToDateTime(((TextBox)row.FindControl("ExpirationDate")).Text).ToString("yyyy:MM:dd hh:mm:ss") +
                "', (SELECT ID FROM BookQuest WHERE EAN = '" + row.Cells[0].Text + "'));";

            result = DBOperations.Execute(true, CommandType.Text, null, commandText, null);
            if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
            {
                FailedInsertsEAN += ((FailedInsertsEAN == string.Empty) ? "" : ", ") + row.Cells[0].Text;
                continue;
            }
        }

        if (FailedUpdatesEAN != string.Empty || FailedInsertsEAN != string.Empty)
        {
            string warning = string.Empty;

            if (FailedUpdatesEAN != string.Empty)
            {
                warning = "Failed to update Tantor Statur for products with following EAN: <br> " + FailedUpdatesEAN + ".<br><br>";
            }
            if (FailedInsertsEAN != string.Empty)
            {
                warning = "Updated Tantor Status, but failed to enter offer details for products with the following EAN: <br> " + FailedInsertsEAN + ".";
            }
            SetWarningLabel(warning);
        }
        Filter();
    }

    protected void btnSubmitOnHold_Click(object sender, EventArgs e)
    {
        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
            return;

        StringBuilder commandText = new StringBuilder(
            "UPDATE BookQuest SET TantorStatus = 4, Color = " + ColorTranslator.ToOle(Color.Red) +
            ", Comments = '" + txtOnHoldComment.Text +
            "' WHERE EAN IN(", 500);
        foreach (string EAN in keys.Keys)
        {
            commandText.Append("'" + EAN + "',");
        }
        // replace the last comma with a closing bracket
        commandText = commandText.Replace(',', ')', commandText.Length - 1, 1);

        object result = DBOperations.Execute(true, CommandType.Text, null, commandText.ToString(), null);
        int recordsUpdated = 0;
        if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
        {
            SetWarningLabel("Failed to update Tantor Status: <br>" + result.ToString());
        }
        else
        {
            Filter();
        }
    }

    protected void btnSubmitAssignTitle_Click(object sender, EventArgs e)
    {
        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
            return;

        StringBuilder commandText = new StringBuilder(
            "UPDATE BookQuest SET AssignedTo = " + ddlUser.SelectedValue +
            " WHERE EAN IN(", 500);
        foreach (string EAN in keys.Keys)
        {
            commandText.Append("'" + EAN + "',");
        }
        // replace the last comma with a closing bracket
        commandText = commandText.Replace(',', ')', commandText.Length - 1, 1);

        object result = DBOperations.Execute(true, CommandType.Text, null, commandText.ToString(), null);
        int recordsUpdated = 0;
        if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
        {
            SetWarningLabel("Failed to assign selected titles: <br>" + result.ToString());
        }
        else
        {
            Filter();
        }
    }

    protected void btnSubmitCancel_Click(object sender, EventArgs e)
    {
        var keys = Session["CHECKED_ITEMS"] as Dictionary<string, Offer>;

        if (keys == null || keys.Count == 0)
            return;

        string commandText;
        string FailedUpdatesEAN = string.Empty;
        string FailedInsertsEAN = string.Empty;

        foreach (GridViewRow row in CancelGridView.Rows)
        {
            commandText =
                "UPDATE BookQuest SET TantorStatus = 0, Color = " + ColorTranslator.ToOle(Color.Transparent) +
                ", Comments = '" + ((TextBox)row.FindControl("Comments")).Text +
                "'  WHERE EAN = '" + row.Cells[0].Text + "';";

            object result = DBOperations.Execute(true, CommandType.Text, null, commandText, null);
            int recordsUpdated = 0;
            if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
            {
                FailedUpdatesEAN += ((FailedUpdatesEAN == string.Empty) ? "" : ", ") + row.Cells[0].Text;
                continue;
            }

            commandText = "INSERT INTO BookQuest_Cancel (Reason, CancelTime, BookQuestID) VALUES(" + ((DropDownList)row.FindControl("Reason")).SelectedValue +
              ", '" + DateTime.Now.ToString("yyyy:MM:dd hh:mm:ss") +
              "', (SELECT ID FROM BookQuest WHERE EAN = '" + row.Cells[0].Text + "'));";

            result = DBOperations.Execute(true, CommandType.Text, null, commandText, null);
            if (result != null && !Int32.TryParse(result.ToString(), out recordsUpdated)) // exception was thrown: if the returned value is not the number of updated records, it is an error message
            {
                FailedInsertsEAN += ((FailedInsertsEAN == string.Empty) ? "" : ", ") + row.Cells[0].Text;
                continue;
            }
        }

        if (FailedUpdatesEAN != string.Empty || FailedInsertsEAN != string.Empty)
        {
            string warning = string.Empty;

            if (FailedUpdatesEAN != string.Empty)
            {
                warning = "Failed to update Tantor Statur for products with following EAN: <br> " + FailedUpdatesEAN + ".<br><br>";
            }
            if (FailedInsertsEAN != string.Empty)
            {
                warning = "Updated Tantor Status, but failed to enter cancellation reason for products with the following EAN: <br> " + FailedInsertsEAN + ".";
            }
            SetWarningLabel(warning);
        }
        Filter();
    }

    protected void btnSubmitImport_Click(object sender, EventArgs e)
    {
        if (importFilePath.HasFile)
        {
            FileToImport = Server.MapPath(".") + "/Temp/temp.xls";
            importFilePath.SaveAs(FileToImport);   //temporarily saves the file to work with (will be cleaned up two lines down)
            EnableImportControls(false);
            ImportFile();
            File.Delete(FileToImport);//cleans up the temporary file that was stored
            EnableImportControls(true);
        }
    }

    protected void btnSubmitOrderBy_Click(object sender, EventArgs e)
    {
        Session["OrderBy"] = SelectedItems.Value.TrimEnd(',');

        Filter();
    }

    protected void btnSubmitHideColumns_Click(object sender, EventArgs e)
    {
        string selectedFields = string.Empty;

        if (lstFields.GetSelectedIndices().Count() > 0)
        {
            foreach (int index in lstFields.GetSelectedIndices())
            {
                selectedFields += lstFields.Items[index].Text + "#";
            }
            selectedFields = selectedFields.TrimEnd('#');

            //HiddenColumns = selectedFields;

            //Response.Cookies["HiddenColumns"].Value = selectedFields;
            //Response.Cookies["HiddenColumns"].Expires = DateTime.Now.AddDays(365);
        }
        HiddenColumns = selectedFields;

        //else
        //{
        //    Response.Cookies["HiddenColumns"].Expires = DateTime.Now.AddDays(-1);
        //}
        Response.Redirect(Request.Path);
    }

    protected void btnSubmitFilterByLicensors_Click(object sender, EventArgs e)
    {
        string licensorsToFilterBy = string.Empty;
        if (lstLicensors.GetSelectedIndices().Count() > 0)
        {
            foreach (int index in lstCustomViewsLicensors.GetSelectedIndices())
            {
                licensorsToFilterBy += lstLicensors.Items[index].Text + "#";
            }
            licensorsToFilterBy = licensorsToFilterBy.TrimEnd('#');

            Session["LicensorsToOrderBy"] = SelectedItems.Value.TrimEnd(',');
        }
        else
        {
            Session["LicensorsToOrderBy"] = null;
        }
        Filter();
    }

    protected void btnSaveCustomViews_Click(object sender, EventArgs e)
    {
        SaveCustomView(false);
    }

    protected void btnSaveAndApplyCustomViews_Click(object sender, EventArgs e)
    {
        SaveCustomView(true);
    }

    protected void HasFileCustomValidate(object sender, ServerValidateEventArgs e)
    {
        if (!importFilePath.HasFile)
        {
            e.IsValid = false;
        }
    }

    #endregion

    #endregion

    #region Methods

    protected string GenerateWhereClause()
    {
        string strWHERE = string.Empty;
        int criterion = 0;
        FILTERING_CRITERIA filteringCriteria = FILTERING_CRITERIA.CUSTOM_VIEW;

        if (Int32.TryParse(ddlFilter.SelectedValue, out criterion) == true)
        {
            filteringCriteria = (FILTERING_CRITERIA)criterion;
        }

        if (filteringCriteria == FILTERING_CRITERIA.EXISTING_AUTHORS)  // if we want titles of authors that exist in the Authors table
        {
            strWHERE += " JOIN Authors a ON b.RespParty LIKE CONCAT(a.LastName, '%', a.FirstName, '%')";
        }

        strWHERE += @"LEFT OUTER JOIN User u ON b.AssignedTo = u.ID
                      LEFT OUTER JOIN 
                        (SELECT Amount, OfferDate, ID, BookQuestID FROM BookQuest_Offer
                        WHERE ID = (SELECT MAX(ID) FROM BookQuest_Offer bobo WHERE bobo.ID = ID))
                      bo
                        ON b.ID = bo.BookQuestID
                      WHERE Binding <> 'CD/Spoken Word' ";

        if (filteringCriteria != FILTERING_CRITERIA.CANCELLED)
            strWHERE += " AND (TantorStatus IS NULL OR TantorStatus <> 0) ";

        if (filteringCriteria != FILTERING_CRITERIA.ALL && filteringCriteria != FILTERING_CRITERIA.CUSTOM_VIEW)   // if not All and not a Custom View is selected
        {
            strWHERE += " AND ";
            if (filteringCriteria == FILTERING_CRITERIA.MY_TITLES)  // if we want My Titles
            {
                strWHERE += " AssignedTo = (SELECT ID FROM User WHERE Name = '" + Page.User.Identity.Name + "')";
            }
            else if (filteringCriteria == FILTERING_CRITERIA.EXISTING_AUTHORS)  // if we want titles of authors that exist in the Authors table
            {
                strWHERE += " RespParty LIKE CONCAT(a.LastName, '%', a.FirstName, '%')";
            }
            else                         // if we filter by Tantor Status
            {
                strWHERE += " TantorStatus = " + (int)filteringCriteria;
            }
        }

        if (From.Text != string.Empty)
        {
            strWHERE += " AND " + ddlDatesToFilterBy.SelectedValue + " >= '" + string.Format("{0:yyyy/M/d}", Convert.ToDateTime(From.Text)) + "'";
        }
        if (To.Text != string.Empty)
        {
            strWHERE += " AND " + ddlDatesToFilterBy.SelectedValue + " <= '" + string.Format("{0:yyyy/M/d}", Convert.ToDateTime(To.Text)) + "'";
        }

        if (txtFilterValue.Text != string.Empty && ddlBookQuestFields.SelectedValue.ToString() != "*None")
        {
            string filteringText = txtFilterValue.Text.Replace("'", "''");
            strWHERE += " AND " + ddlBookQuestFields.SelectedValue;

            if (ddlBookQuestFields.SelectedValue == "AssignedTo")
                strWHERE += " = (SELECT ID FROM user WHERE Name LIKE '%" + filteringText + "%')";
            else
            {
                switch (dbColumns[ddlBookQuestFields.SelectedValue])
                {
                    case "String":
                        strWHERE += " LIKE '%" + filteringText + "%'";
                        break;
                    case "Boolean":
                    case "Int32":
                    case "Byte":
                    case "Decimal":
                    case "Single":
                    case "Double":
                        strWHERE += " = " + txtFilterValue.Text;
                        break;
                    case "DateTime":
                        DateTime dt = Convert.ToDateTime(filteringText);
                        strWHERE += " = '" + dt.ToString("yyyy-MM-dd") + "'";
                        break;
                }
            }
        }

        if (Session["LicensorsToFilterBy"] != null)
        {
            string[] licensorsToFilterBy = Session["LicensorsToFilterBy"].ToString().Split('#');
            if (licensorsToFilterBy.Length > 0)
            {
                strWHERE += " AND Licensor IN(";
                foreach (string licensor in licensorsToFilterBy)
                {
                    strWHERE += "'" + licensor + "',";
                }
                strWHERE = strWHERE.TrimEnd(',');
                strWHERE += ") ";
            }
        }

        return strWHERE;
    }

    public void Filter()
    {
        SqlDataSource FrontListSqlDataSource = GetControl(this, "FrontListSqlDataSource") as SqlDataSource;
        FrontListSqlDataSource.SelectCommand = selectAllBookQuest + GenerateWhereClause();

        if (Session["OrderBy"] != null && (Session["OrderBy"]).ToString() != string.Empty)
        {
            FrontListSqlDataSource.SelectCommand += " ORDER BY " + (Session["OrderBy"]).ToString();
        }

        Session["LicensingSelect"] = FrontListSqlDataSource.SelectCommand; // We will need it for printing and exporting the GridView contents

        int LicensingPageIndex = (Session["LicensingPageIndex"] == null) ? 0 : (int)Session["LicensingPageIndex"];
        FrontListSqlDataSource.SelectCommand += " LIMIT " + (LicensingPageIndex * FrontListGridView.PageSize) + ", " + (FrontListGridView.PageSize) + ";";

        FrontListGridView.DataBind();
        Session["LicensingSavedPage"] = txtGoToPage.Text;   // we save current page because if this postback is on txtGoToPage, we will use it to set the page, because txtGoToPage will already be reset below
        txtGoToPage.Text = (Session["LicensingPageIndex"] == null) ? "1" : ((int)Session["LicensingPageIndex"] + 1).ToString();
        lblTotalNumberOfPages.Text = (Session["LicensingPageCount"]).ToString();
    }

    public int GetPageCount()
    {
        string commandText = "SELECT COUNT(1) RecordCount FROM BookQuest b " + GenerateWhereClause();

        object result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);

        int count = 0;

        if (result is string)    // an error message was returned
        {
            SetWarningLabel("Failed to get page count: <br>" + result.ToString());
            return 0;
        }
        if (result is OdbcDataReader)
        {
            OdbcDataReader odbcReader = result as OdbcDataReader;
            if (odbcReader.Read())
            {
                count = Convert.ToInt32(odbcReader["RecordCount"]) / FrontListGridView.PageSize + 1;
            }
        }
        return count;
    }

    protected void EnableDisableNavigation()
    {
        int LicensingPageIndex = (Session["LicensingPageIndex"] == null) ? 0 : (int)Session["LicensingPageIndex"];
        btnNext.Enabled = (LicensingPageIndex != (int)Session["LicensingPageCount"] - 1); // disable if it is the last page
        btnPrev.Enabled = (LicensingPageIndex != 0);                             // disable if it is the first page
    }

    protected void EnableImportControls(bool bEnable)
    {
        importFilePath.Enabled = bEnable;
        btnSubmitImport.Enabled = bEnable;
        btnCancelImport.Enabled = bEnable;
    }

    protected void ImportFile()
    {
        // First save whose publishers whose books are to be imported
        string commandText = "{ CALL UpdatePublisherImportFlag(?) }";
        int selectedCount = 0;

        string selectedPublishers = string.Empty;
        foreach (ListItem li in chlstPublishers.Items)
        {
            if (li.Selected == true)
            {
                selectedPublishers += li.Value + ", ";
                selectedCount++;
            }
        }
        selectedPublishers = selectedPublishers.TrimEnd(',', ' ');

        OdbcParameter[] parameters = new OdbcParameter[]{
                new OdbcParameter("pPublisherIDsInClause", selectedPublishers)};

        object result = DBOperations.Execute(true, CommandType.StoredProcedure, null, commandText, parameters);

        if (result is string)    // an error message was returned
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP_PostMessage", "ShowErrors();", true);
            txtError.Text = "Failed to save selected publishers: \n" + result.ToString();
            txtError.Visible = true;
        }

        OdbcConnection odbcConnection = null;

        string[,] sheetEntries = ImportExcelToArray(excelRawColumns, false);

        if (sheetEntries == null)
            return;

        int inserted = 0;
        int updated = 0;
        int failed = 0;
        
        StringBuilder failedEANs = new StringBuilder();
        int rowCounter = 0;
        OdbcDataReader odbcReader = null;
        OdbcCommand odbcCommand = null;
        try
        {
            String odbcConnString = WebConfigurationManager.ConnectionStrings["BookList"].ToString();
            odbcConnection = new OdbcConnection(odbcConnString);

            odbcCommand = new OdbcCommand("{ CALL InsertBookQuest(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) }", odbcConnection);

            odbcCommand.CommandType = CommandType.StoredProcedure;
        }
        catch (OdbcException ex)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP", "ShowImportErrors();", true);
            txtError.Text = "Import failed:<br />" + ex.Message;
            txtError.Visible = true;

            odbcCommand.Dispose();
            odbcCommand = null;
            if (odbcConnection != null && odbcConnection.State == ConnectionState.Open)
            {
                odbcConnection.Close();
                odbcConnection = null;
            }
            return;
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP", "ShowImportErrors();", true);
            txtError.Text = "Import failed:<br />" + ex.Message;
            txtError.Visible = true;

            odbcCommand.Dispose();
            odbcCommand = null;
            if (odbcConnection != null && odbcConnection.State == ConnectionState.Open)
            {
                odbcConnection.Close();
                odbcConnection = null;
            }
            return;
        }

        for (rowCounter = 0; rowCounter < sheetEntries.GetLength(0); rowCounter++)
        {
            try
            {
                #region Set Parameters
                odbcCommand.Parameters.Clear();

                OdbcParameter odbcParameter = odbcCommand.Parameters.Add("pEAN", OdbcType.VarChar, 13);
                odbcParameter.Value = sheetEntries[rowCounter, 0] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 0];
                odbcParameter = odbcCommand.Parameters.Add("pTitle", OdbcType.VarChar, 255);
                odbcParameter.Value = sheetEntries[rowCounter, 1] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 1];
                odbcParameter = odbcCommand.Parameters.Add("pRespParty", OdbcType.VarChar, 255);
                odbcParameter.Value = sheetEntries[rowCounter, 2] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 2];
                odbcParameter = odbcCommand.Parameters.Add("pPublisher", OdbcType.VarChar, 255);
                odbcParameter.Value = sheetEntries[rowCounter, 3] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 3];
                odbcParameter = odbcCommand.Parameters.Add("pPubDate", OdbcType.SmallDateTime);
                odbcParameter.Value = sheetEntries[rowCounter, 4] == "" ? (object)DBNull.Value : Convert.ToDateTime(sheetEntries[rowCounter, 4]);
                odbcParameter = odbcCommand.Parameters.Add("pSubject", OdbcType.VarChar, 255);
                odbcParameter.Value = sheetEntries[rowCounter, 5] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 5];
                odbcParameter = odbcCommand.Parameters.Add("pBinding", OdbcType.VarChar, 45);
                odbcParameter.Value = sheetEntries[rowCounter, 6] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 6];
                odbcParameter = odbcCommand.Parameters.Add("pPageCount", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 7] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 7]);
                odbcParameter = odbcCommand.Parameters.Add("pUSListPrice", OdbcType.Double);
                odbcParameter.Value = sheetEntries[rowCounter, 8] == "" ? (object)DBNull.Value : Convert.ToDouble(sheetEntries[rowCounter, 8]);
                odbcParameter = odbcCommand.Parameters.Add("pDemand", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 9] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 9]);
                odbcParameter = odbcCommand.Parameters.Add("pOnOrder", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 10] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 10]);
                odbcParameter = odbcCommand.Parameters.Add("pOnBackorder", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 11] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 11]);
                odbcParameter = odbcCommand.Parameters.Add("pSpeedStock", OdbcType.Bit);
                if (sheetEntries[rowCounter, 12] == "N" || sheetEntries[rowCounter, 12] == "n")
                    sheetEntries[rowCounter, 12] = "0";
                else if (sheetEntries[rowCounter, 12] == "Y" || sheetEntries[rowCounter, 12] == "y")
                    sheetEntries[rowCounter, 12] = "1";
                odbcParameter.Value = sheetEntries[rowCounter, 12] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 12]);
                odbcParameter = odbcCommand.Parameters.Add("pStatus", OdbcType.VarChar, 45);
                odbcParameter.Value = sheetEntries[rowCounter, 13] == "" ? (object)DBNull.Value : sheetEntries[rowCounter, 13];
                odbcParameter = odbcCommand.Parameters.Add("pBTKey", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 14] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 14]);
                odbcParameter = odbcCommand.Parameters.Add("pBTFirstPrinting", OdbcType.Int);
                odbcParameter.Value = sheetEntries[rowCounter, 15] == "" ? (object)DBNull.Value : Convert.ToInt32(sheetEntries[rowCounter, 15]);

                #endregion

                if (odbcConnection.State == ConnectionState.Closed)
                    odbcConnection.Open();

                // we use ExecuteReader() and not ExecuteNonQuery() because output parameter doesn't work (probably MySql bug?) and we return IsInsert in a result set instead
                odbcReader = odbcCommand.ExecuteReader();

                if (odbcReader.Read())
                {
                    if (Convert.ToBoolean(odbcReader["IsInsert"]) == true)
                        inserted++;
                    else
                        updated++;
                }
            }
            catch (OdbcException ex)
            {
                failed++;
                failedEANs.Append("Line " + (rowCounter + 1) /* + 1 because rowCounter is 0-based */ + ", EAN: " + sheetEntries[rowCounter, 0] + ": " + ex.Message + "\r\n");
            }
            catch (Exception ex)
            {
                failed++;
                failedEANs.Append("Line " + (rowCounter + 1) /* + 1 because rowCounter is 0-based */ + ", EAN: " + sheetEntries[rowCounter, 0] + ": " + ex.Message + "\r\n");
            }
            finally
            {
                if (odbcReader != null && !odbcReader.IsClosed)
                {
                    odbcReader.Close();
                    odbcReader = null;
                }
            }
        }
        odbcCommand.Dispose();
        odbcCommand = null;

        if (odbcConnection != null && odbcConnection.State == ConnectionState.Open)
        {
            odbcConnection.Close();
            odbcConnection = null;
        }

        string msg = inserted + " record(s) inserted and " + updated + " record(s) updated successfully.";
        if (failedEANs.Length == 0)
        {
            SetSuccessLabel(msg);
        }
        else
        {
            string absolutePath = @"C:/Inetpub/wwwroot";
            string relativePath = @"/TPS/Temp/" + System.DateTime.Now.Ticks.ToString() + "_ImportLog.txt";
            StreamWriter log = new StreamWriter(absolutePath + relativePath);
            log.WriteLine(msg + "\r\nFailed to import " + failed + " record(s)");
            log.Write(failedEANs.ToString());
            log.Close();
            SetInfoLabel(msg + Constants.htmlBreak + failed + " record(s) failed. Please see details <A href='" + relativePath + "'> here</A>.");
        }
        Filter();
    }

    protected string[,] ImportExcelToArray(string[] excelColumns, bool bGetColor)
    {
        String oledbConnString;
        string extension = Path.GetExtension(FileToImport);
        switch (extension)
        {
            case ".xls":
                oledbConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileToImport + ";Extended Properties=Excel 8.0;";
                break;
            case ".xlsx":
                oledbConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileToImport + ";Extended Properties=Excel 12.0;";
                break;
            default:
                return null;
        }

        OleDbConnection oledbConnection = new OleDbConnection(oledbConnString);

        Excel.Application oExcel = null;
        Excel.Workbook theWorkbook = null;
        Excel.Worksheet worksheet = null;
        Excel.Sheets sheets = null;

        try
        {
            oledbConnection.Open();
            // generate a list of selected publishers to be used in the IN clause
            string selectedPublishers = string.Empty;
            foreach (ListItem publisher in chlstPublishers.Items)
            {
                if (publisher.Selected == true)
                {
                    selectedPublishers += "'" + publisher.Text.Replace("'", "''") + "', ";
                }
            }
            selectedPublishers = selectedPublishers.TrimEnd(',', ' ');

            //this next part assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
            string excelQuery = "SELECT ";
            foreach (string field in excelColumns)
            {
                excelQuery += "`" + field + "`,";
            }
            excelQuery = excelQuery.TrimEnd(',');
            excelQuery += " FROM [Sheet1$] WHERE Publisher IN (" + selectedPublishers + ");";

            var adapter = new OleDbDataAdapter(excelQuery, oledbConnection);
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            adapter.Fill(dt);//overwrites the previous declaration with the same information
            //now you have your datatable filled and ready for manipulation

            oledbConnection.Close();

            int number_of_columns = dt.Columns.Count;
            int number_of_rows = dt.Rows.Count;
            string[,] sheetEntries = new string[number_of_rows, number_of_columns + (bGetColor ? 1 : 0)]; // + 1 for storing color

            if (bGetColor)
            {
                oExcel = new Excel.Application();
                theWorkbook = oExcel.Workbooks.Open(FileToImport, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, true, false);
                sheets = theWorkbook.Worksheets;
                worksheet = (Excel.Worksheet)sheets.get_Item(1);
            }

            //gets excel spreadsheet information
            for (int i = 0; i < number_of_rows; i++)
            {
                int j;
                for (j = 0; j < number_of_columns; j++)
                    sheetEntries[i, j] = dt.Rows[i].ItemArray.GetValue(j).ToString();

                if (bGetColor && worksheet != null)   // add color in the last column
                    sheetEntries[i, j] = worksheet.get_Range("B" + (i + 2), "B" + (i + 2)).Interior.Color.ToString();  // i + 2 because 1) excel rows are not 0-based, and 2) the first row is header and not data
            }
            return sheetEntries;
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP", "ShowImportErrors();", true);
            txtError.Text = ex.Message;
            txtError.Visible = true;
            return null;
        }
        finally
        {
            if (oledbConnection != null && oledbConnection.State == ConnectionState.Open)
                oledbConnection.Close();
        }
    }

    // Save keys of the checked rows on the current GridView page
    public void RememberOldValues()
    {
        if (FrontListGridView.DataKeys.Count == 0)
            return;
        var keys = new Dictionary<string, Offer>();
        string id;
        foreach (GridViewRow row in FrontListGridView.Rows)
        {
            id = FrontListGridView.DataKeys[row.RowIndex].Value.ToString();
            bool result = ((CheckBox)row.FindControl("BookSelector")).Checked;

            // Check in the Session

            if (Session["CHECKED_ITEMS"] != null)
                keys = (Dictionary<string, Offer>)Session["CHECKED_ITEMS"];

            if (result)
            {
                DateTime pubDate = DateTime.MinValue;
                DateTime.TryParse((row.Cells[(int)SOME_COLUMNS.PUB_DATE].Controls[1] as Label).Text, out pubDate);    // 9 corresponds to PubDate column

                keys[id] = new Offer(id,
                    pubDate,
                    (row.Cells[(int)SOME_COLUMNS.OFFER_AMOUNT].Controls[1] as Label).Text == string.Empty ? 0 :
                    Convert.ToDouble((row.Cells[(int)SOME_COLUMNS.OFFER_AMOUNT].Controls[1] as Label).Text.TrimStart('$')));    // 24 corresponds to OfferAmount column
            }
            else
                keys.Remove(id);
        }
        if (keys != null && keys.Count > 0)
            Session["CHECKED_ITEMS"] = keys;
    }

    // Check the GridView rows whose keys were stored in the Session
    public void RePopulateValues()
    {
        Dictionary<string, Offer> keys = (Dictionary<string, Offer>)Session["CHECKED_ITEMS"];

        if (keys != null && keys.Count > 0)
        {
            foreach (GridViewRow row in FrontListGridView.Rows)
            {
                string id = FrontListGridView.DataKeys[row.RowIndex].Value.ToString();
                if (keys.ContainsKey(id))
                {
                    CheckBox myCheckBox = (CheckBox)row.FindControl("BookSelector");
                    myCheckBox.Checked = true;
                }
            }
        }
    }

    protected void HideFields()
    {        
        // Find the table that serves as a header for the GridView
        var header = GetControl(this, "FrontListGridViewHeader") as System.Web.UI.HtmlControls.HtmlTable;

        // First make all data fields visible
        for (int index = _firstEditCellIndex, headerIndex = _firstEditHeaderColumnIndex; index < FrontListGridView.Columns.Count; index++, headerIndex++)
        {
            FrontListGridView.Columns[index].Visible = true;
            header.Rows[0].Cells[headerIndex].Visible = true; 
        }

        if (Request.Cookies["HiddenColumns"] != null)
        {
            string strHiddenColumns = HiddenColumns;

            string[] hiddenColumns = strHiddenColumns.Split('#');

            for (int index = _firstEditCellIndex, headerIndex = _firstEditHeaderColumnIndex; index < FrontListGridView.Columns.Count; index++, headerIndex++)
            {
                foreach (string field in hiddenColumns)
                {
                    if (field == FrontListGridView.Columns[index].HeaderText.Replace(" ", ""))
                    {
                        FrontListGridView.Columns[index].Visible = false;
                        header.Rows[0].Cells[headerIndex].Visible = false;
                        break;
                    }
                }
            }
        }
    }

    protected void SaveCustomView(bool bApply)
    {
        Page.Validate("cvfilter");
        if (!IsCustomViewsValid)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP_CustomView", "ShowCustomViewErrors();", true);
            return;
        }

        string hiddenFields = string.Empty;
        if (lstCustomViewsFields.GetSelectedIndices().Count() > 0)
        {
            foreach (int index in lstCustomViewsFields.GetSelectedIndices())
            {
                hiddenFields += lstCustomViewsFields.Items[index].Text + "#";
            }
            hiddenFields = hiddenFields.TrimEnd('#');
        }

        string licensorsToFilterBy = string.Empty;
        if (lstCustomViewsLicensors.GetSelectedIndices().Count() > 0)
        {
            foreach (int index in lstCustomViewsLicensors.GetSelectedIndices())
            {
                licensorsToFilterBy += lstCustomViewsLicensors.Items[index].Text + "#";
            }
            licensorsToFilterBy = licensorsToFilterBy.TrimEnd('#');
        }

        string commandText = "{ CALL InsertUpdateCustomView(?, ?, ?, ?, ?, ?, ?, ?) }";
        var parameters = new OdbcParameter[8];
        parameters[0] = new OdbcParameter("pName", txtCustomViewName.Text);
        parameters[1] = new OdbcParameter("pFilterField", ddlCVBookQuestFields.SelectedValue);
        parameters[2] = new OdbcParameter("pFilterValue", txtCVFilterValue.Text);
        string strOrderBy = SelectedItems.Value.TrimEnd(',');
        parameters[3] = new OdbcParameter("pOrderBy", strOrderBy);
        parameters[4] = new OdbcParameter("pHiddenFields", hiddenFields);
        parameters[5] = new OdbcParameter("pLicensorsToFilterBy", licensorsToFilterBy);
        parameters[6] = new OdbcParameter("pIsPrivate", rdoPrivate.Checked);
        parameters[7] = new OdbcParameter("pUserName", Page.User.Identity.Name);

        object result = DBOperations.Execute(true, CommandType.StoredProcedure, null, commandText, parameters);
        if (result is string)    // an error message was returned
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "openMP_CustomView", "ShowCustomViewErrors();", true);
            txtCVError.Text = "Failed to save Custom View.\n" + result.ToString();
            txtCVError.Visible = true;
        }
        else
        {
            if (bApply)
            {
                Session["OrderBy"] = strOrderBy;

                HiddenColumns = hiddenFields;

                Session["FilterField"] = ddlCVBookQuestFields.SelectedValue;
                Session["FilterValue"] = txtCVFilterValue.Text;
                Session["LicensorsToFilterBy"] = licensorsToFilterBy;

                ddlBookQuestFields.SelectedValue = ddlCVBookQuestFields.SelectedValue;
                txtFilterValue.Text = txtCVFilterValue.Text;

                Filter();
                HideFields();
            }
            CustomViewName = txtCustomViewName.Text;
            UpdateDDLFilterWithCustomViews();

            SetSuccessLabel("Custom View '" + CustomViewName + "' was successfully saved.");
        }
    }

    protected void UpdateDDLFilterWithCustomViews()
    {
        string commandText = @"SELECT Name, FilterField, FilterValue, OrderBy, HiddenFields, LicensorsToFilterBy, IsPrivate FROM CustomView
                                   WHERE IsPrivate = 0 OR UserName = '" + Page.User.Identity.Name + "' ORDER BY Name;";
        object result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);
        if (result is string)    // an error message was returned
        {
            SetWarningLabel("Failed to retrieve Custom Views data: <br>" + result.ToString());
        }
        else if (result is OdbcDataReader)
        {
            // Clear all previously existed Custom View items
            for (int index = FIRST_CUSTOMVIEWS_INDEX - 1; index < ddlFilter.Items.Count;)
            {
                ddlFilter.Items.RemoveAt(index); // index stays the same, because with every iteration the next item replaces the deleted one
            }

            // Place *** to separate Custom Vies from other filter options
            ListItem separatorItem = new ListItem();
            separatorItem.Attributes.Add("style", "color:gray;");
            separatorItem.Attributes.Add("disabled", "true");
            separatorItem.Value = "***";
            ddlFilter.Items.Add(separatorItem);

            var customViews = Session["CustomViews"] as Dictionary<string, CustomView>;
            if (customViews == null)
                customViews = new Dictionary<string, CustomView>();
            else
                customViews.Clear();

            OdbcDataReader odbcReader = result as OdbcDataReader;
            while (odbcReader.Read())
            {
                string customViewName = odbcReader["Name"].ToString();
                ddlFilter.Items.Add(customViewName);
                customViews[customViewName] = new CustomView(odbcReader["FilterField"].ToString(),
                                                             odbcReader["FilterValue"].ToString(),
                                                             odbcReader["OrderBy"].ToString(),
                                                             odbcReader["HiddenFields"].ToString(),
                                                             odbcReader["LicensorsToFilterBy"].ToString(),
                                                             Convert.ToBoolean(odbcReader["IsPrivate"]));
            }
            Session["CustomViews"] = customViews;
            if (CustomViewName != null)
                ddlFilter.SelectedValue = CustomViewName; 
        }
    }

    protected void ShowLicensingDetail(int rowIndex)
    {
        if (rowIndex > -1)
        {
            string commandText = @"SELECT EAN, TantorStatus, AssignedTo, 
            Title, RespParty, Publisher, PubDate, Subject, Binding, PageCount, USListPrice, Demand, OnOrder, OnBackorder, SpeedStock, Status, BTKey,
            FirstPrinting, Ingram, Licensor, LastDate, Comments, Note, FirstAppearance, Material, UnitSales
            From BookQuest WHERE EAN = '" +
                FrontListGridView.DataKeys[rowIndex].Value.ToString() + "';";

            object result = DBOperations.Execute(false, CommandType.Text, null, commandText, null);

            if (result is string)    // an error message was returned
            {
                SetWarningLabel("Failed to get Licensing information: <br>" + result.ToString());
                return;
            }
            if (result is OdbcDataReader)
            {
                OdbcDataReader odbcReader = result as OdbcDataReader;
                if (odbcReader.Read())
                {
                    EAN.Text = odbcReader["EAN"].ToString();
                    TantorStatus.SelectedValue = odbcReader["TantorStatus"].ToString();
                    AssignedTo.SelectedValue = odbcReader["AssignedTo"].ToString();
                    Title.Text = odbcReader["Title"].ToString();
                    RespParty.Text = odbcReader["RespParty"].ToString();
                    Publisher.Text = odbcReader["Publisher"].ToString();
                    DateTime pubDate;
                    PubDate.Text = DateTime.TryParse(odbcReader["PubDate"].ToString(), out pubDate) == true ? 
                        pubDate.ToShortDateString() : string.Empty;
                    Subject.Text = odbcReader["Subject"].ToString();
                    Binding.Text = odbcReader["Binding"].ToString();
                    PageCount.Text = odbcReader["PageCount"].ToString();
                    USListPrice.Text = odbcReader["USListPrice"].ToString();
                    Demand.Text = odbcReader["Demand"].ToString();
                    OnOrder.Text = odbcReader["OnOrder"].ToString();
                    OnBackorder.Text = odbcReader["OnBackorder"].ToString();
                    SpeedStock.Checked = (bool)odbcReader["SpeedStock"];
                    Status.Text = odbcReader["Status"].ToString();
                    BTKey.Text = odbcReader["BTKey"].ToString();
                    FirstPrinting.Text = odbcReader["FirstPrinting"].ToString();
                    Ingram.Text = odbcReader["Ingram"].ToString();
                    Licensor.Text = odbcReader["Licensor"].ToString();
                    LastDate.Text = (odbcReader["LastDate"] == DBNull.Value) ? string.Empty : string.Format("{0:M/d/yyyy}", (DateTime)odbcReader["LastDate"]);
                    Comments.Text = odbcReader["Comments"].ToString();
                    Note.Text = odbcReader["Note"].ToString();
                    FirstAppearance.Text = (odbcReader["FirstAppearance"] == DBNull.Value) ? string.Empty : string.Format("{0:M/d/yyyy}", (DateTime)odbcReader["FirstAppearance"]);
                    Material.Text = odbcReader["Material"].ToString();
                    UnitSales.Text = odbcReader["UnitSales"].ToString();
                }
                else
                {
                    ClearLicensingDetail();
                }
            }
        }
        else
        {
            ClearLicensingDetail();
        }
        txtLDError.Visible = false;

        LicensingDetailModalPopupExtender.Show();
    }

    void ClearLicensingDetail()
    {
        EAN.Text = Title.Text = RespParty.Text = Publisher.Text = PubDate.Text = Subject.Text =
        Binding.Text = PageCount.Text = USListPrice.Text = Demand.Text = OnOrder.Text =
        OnBackorder.Text = Status.Text = BTKey.Text = FirstPrinting.Text = Ingram.Text =
        Licensor.Text = LastDate.Text = Comments.Text = Note.Text = FirstAppearance.Text =
        Material.Text = UnitSales.Text = string.Empty;
        TantorStatus.SelectedValue = AssignedTo.SelectedValue = string.Empty;
    }

    //[System.Web.Services.WebMethod]
    //[System.Web.Script.Services.ScriptMethod]
    //public static void DeleteCustomView(string customViewName)
    //{
    //    string commandText = "{ CALL DeleteCustomView(?) }";
    //    var parameters = new OdbcParameter[1];
    //    parameters[0] = new OdbcParameter("pName", customViewName);

    //    object result = DBOperations.Execute(true, CommandType.StoredProcedure, null, commandText, parameters);
    //    if (result is string)    // an error message was returned
    //    {
    //        throw new Exception(result as string);
    //    }
    //}

    public bool IsValid
    {
        get
        {
            return filterValidator.IsValid;
        }
    }
    public bool IsCustomViewsValid
    {
        get
        {
            return cvFilterValidator.IsValid;
        }
    }

    #endregion
}

Open in new window

0
 
LVL 2

Accepted Solution

by:
SandyAgo earned 2000 total points
ID: 33583641
Try this for your switch statement:
switch (tpsActiveTabIndex)
        {
            case 0:
                UserControl uc1 = (UserControl)Page.LoadControl("~/Licensing.ascx");
		uc1.ID = "ucLicensingControl";
                LicensingPlaceHolder.Controls.Add(uc1);
                this.AddGridViewClasses(uc1.Controls);
                break;
            case 1:
                UserControl uc2 = (UserControl)Page.LoadControl("~/Production.ascx");
		uc2.ID = "ucProductionControl";
                ProductionPlaceHolder.Controls.Add(uc2);
                this.AddGridViewClasses(uc2.Controls);
                break;
            case 2:
                UserControl uc3 = (UserControl)Page.LoadControl("~/Marketing.ascx");
		uc3.ID = "ucMarketingControl";
                MarketingPlaceHolder.Controls.Add(uc3);
                this.AddGridViewClasses(uc3.Controls);
                break;
            case 3:
                UserControl uc4 = (UserControl)Page.LoadControl("~/Database.ascx");
		uc4.ID = "ucDatabaseControl";
                DatabasePlaceHolder.Controls.Add(uc4);
                this.AddGridViewClasses(uc4.Controls);
                break;
            default:
                break;
        }
        this.Page.Header.Controls.Add(new StyleTag() { FontSize = this.FontSize });
    }

Open in new window

0
 

Author Comment

by:tantormedia
ID: 33587647
No, unfortunately, assigning IDs didn't help...
0
 

Author Comment

by:tantormedia
ID: 33590751
I replaced GridView with dynamicallay created controls, and that worked. I still wish to know what was wrong with GridView.
0
 
LVL 4

Expert Comment

by:MichaelMH
ID: 33656059
1. Do you have the view state eneabled?
2. Instead of doing the second .DataBind() on the button handler try to do it on every page Load event. You can detect who triggered the postback event.  
0
 
LVL 4

Expert Comment

by:MichaelMH
ID: 33656070
Sorry, I forgot about solution 3.

3.Make sure that your datasource is not empty on the button event DataBind.
0
 

Author Comment

by:tantormedia
ID: 33665961
I do have my ViewState enabled, so I don't know why the data was not preserved.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question