multi-tab/panel control does not always respond correctly - c#

I have tabs that open and close panels. Multiple tabs/panels can be open at a time. Followed is my current solution:
protected static int[] tabControls = { 0, 0 };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
storyPanel.Visible = true;
hoursPanel.Visible = false;
}
}
/* ===== TAB CONTROLS ===== */
protected void Tab1_Click(object sender, EventArgs e)
{
if (tabControls[0] == 1)
{
storyPanel.Visible = true;
Tab1.CssClass = "Clicked";
tabControls[0] = 0;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#storyPostBack';", true);
}
else
{
storyPanel.Visible = false;
Tab1.CssClass = "Initial";
tabControls[0] = 1;
}
}
protected void Tab2_Click(object sender, EventArgs e)
{
if (tabControls[1] == 1)
{
hoursPanel.Visible = true;
Tab2.CssClass = "Clicked";
tabControls[1] = 0;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#hoursPostBack';", true);
}
else
{
hoursPanel.Visible = false;
Tab2.CssClass = "Initial";
tabControls[1] = 1;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#storyPostBack';", true);
}
}
Sometimes the tab needs to be pressed twice for it to respond and open the panel as well as receive the css changes to itself. I cant figure out why. Additionally, is there a better approach.
EDIT:
It's actually not tabs, sorry for not being clear. It's the illusion of tabs using buttons/panels/css:
Server controls:
<table width="80%" align="center">
<tr>
<td>
<asp:Button Text="Tab 1" BorderStyle="None" ID="Tab1" CssClass="Initial" runat="server"
OnClick="Tab1_Click" />
<asp:Button Text="Tab 2" BorderStyle="None" ID="Tab2" CssClass="Initial" runat="server"
OnClick="Tab2_Click" />
<asp:Panel ID="storyPanel" runat="server">
<table style="width: 100%; border-width: 1px; border-color: #666; border-style: solid">
<tr>
<td>
<h3>
<span>tab content here </span>
</h3>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="hoursPanel" runat="server">
<table style="width: 100%; border-width: 1px; border-color: #666; border-style: solid">
<tr>
<td>
<h3>
tab 2 content here
</h3>
</td>
</tr>
</table>
</asp:Panel>
</table>

It looks to me like the initial state of all tabs is visible:
protected static int[] tabControls = { 0, 0 };
But in fact, only one tab would actually be visible right? Or are all the panels supposed to be visible at the same time? If your tabControls variable is out of sync with the actual visibility of the panels, it may require clicking twice. Once to change the tabControls to invisible, and then one to change it back to visible again. To fix, just do:
protected static int[] tabControls = { 0, 1 };

Related

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

Header not repeating after page break

I added a page break after every 20 rows in a DataGrid. After the page break I want to display the header on top of each page.
I added a thead tag around the header:
<thead>
<tr id="trHeader" runat="server">
<td style="border-width:1px;text-align:left;padding:10px;font-size:26px;">
<div>
<strong><label runat="server" id="lblInvCredNo"></label> </strong><asp:Label runat="server" ID="lblQuoteNo"></asp:Label>
</div>
</td>
<td style="border-width:1px;text-align:left;padding:10px;font-size:26px;">
<div>
<strong><label runat="server" id="lblIvnCredDate"></label> </strong><asp:Label runat="server" ID="lblQuoteDate"></asp:Label>
</div>
</td>
</tr>
</thead>
I added code to the css:
#media print {
.pagebreak {
page-break-after:always;
}
thead {display: table-header-group;}
}
To put the page break after the 20th row in the grid I used this code:
private int count = 1;
public void dgDetails_Bind(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)
{
if ((count % 20) == 0)
{
e.Item.Cells[e.Item.Cells.Count - 1].Text = e.Item.Cells[e.Item.Cells.Count - 1].Text +
"</td><tr class=\"pagebreak\"><td colspan='" +
e.Item.Cells.Count + "'><div class=\"pagebreak\"></div>";
e.Item.CssClass = "pagebreak";
}
count++;
}
}
Do I need to add something to this function to show the header after the page break?

How to show/hide a button from server side?

I'm new to ASP.NET and C#, I tried few things but did not worked. I have an .aspx page where I have three buttons, as shown in below code:
<body>
<form id="htmlForm" runat="server">
<telerik:RadScriptManager ID="rsm" AsyncPostBackTimeout="1800" runat="server" />
<telerik:RadAjaxPanel ID="rap" runat="server" LoadingPanelID="ralp">
<table>
<tr>
<td colspan="2">
Invoice Download
</td>
</tr>
<tr>
<td>
Invoice Start #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbStart" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td>
Invoice End #
</td>
<td>
<telerik:RadNumericTextBox ID="rntbEnd" Runat="server" MaxValue="1000000" MinValue="1000" Width="75px" >
<NumberFormat DecimalDigits="0" GroupSeparator="" />
</telerik:RadNumericTextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="cmdDownload" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" runat="server" Text="Download SAP" />
</td>
</tr>
</table>
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</telerik:RadAjaxPanel>
<telerik:RadAjaxLoadingPanel ID="ralp" Runat="server" Skin="Default" />
<asp:Button ID="btnConform" Visible="false" runat="server" Text="Conform Download" OnClick="btnConform_Click" />
</form>
I'm trying to do that btnConform will be initially invisible while the page is loading and now if I click cmdDownload or cmdDownloadSAP, button btnConform must get visible. Now if I click again on btnConform it will become invisible.
I cannot use JavaScript because cmdDownload and cmdDownloadSAP have some other task to complete before I make btnConform visible (say database call) and the btnConform will become visible only if the database call is successful.
partial class XPO_Accounting_InvoiceDownload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdDownload_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
protected void cmdDownload0_Click(object sender, System.EventArgs e)
{
Session["InvoiceStart"] = rntbStart.Value;
Session["InvoiceEnd"] = rntbEnd.Value;
try
{
//All DB call
btnConform.Visible = true;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
cmdDownload.Click += cmdDownload_Click;
cmdDownloadSAP.Click += cmdDownload0_Click;
}
protected void btnConform_Click(object sender, EventArgs e)
{
double InvoiceStart = (double)Session["InvoiceStart"];
double InvoiceEnd = (double)Session["InvoiceEnd"];
try
{
SqlHelper.ExecuteNonQuery(XPOStaticData.Instance.SQL, CommandType.Text, "update tblInvoiceNum set uploadedtoacct = 'Y' WHERE Status='I' AND InvoiceNum BETWEEN " + InvoiceStart + " AND " + InvoiceEnd + " and uploadedtoacct = 'N'");
lblResult.Text = "Downloaded Invoiced has conformed as the correct one.";
btnConform.Visible = false;
}
catch (Exception ex)
{
lblResult.Text = ex.ToString();
}
}
}
This does not work.
Sorry for change the content of the question (cause older content wasn't pointing the problem properly). This is actual code here I'm trying to do it. (it looks stupid to pest the complete code...)
Add the Visible property to the Button using markup to initially set the second button's visibility:
<asp:Button ID="btnOne" runat="server" Text="One" OnClick="btnOne_Click" />
<asp:Button ID="btnTwo" runat="server" Visible="False" Text="Two" OnClick="btnTwo_Click" />
And on the event handlers, add this:
protected void btnOne_Click(object sender, EventArgs e)
{
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
btnTwo.Visible = false;
}
You change visibility with the Visible property:
protected void btnOne_Click(object sender, EventArgs e)
{
//require code to make it visible
btnTwo.Visible = true;
}
protected void btnTwo_Click(object sender, EventArgs e)
{
//require code to make it invisible
btnTwo.Visible = false;
}
If you want to make a server control initially invisible you also have to use this property, so you can either use codebehind to change visibility programmatically ore declaratively on the aspx-page:
<asp:Button ID="btnTwo" Visible="false" runat="server" Text="Two" OnClick="btnTwo_Click" />
One final note, Visible=false on serverside means that this control is not rendered at all on client-side. So it does simply not exist and can not be accessed (or made visible) on client-side.
If you need to access it on client-side you should make it invisible via stylesheets either by using
display: none(does not take up any space) or
visibility: hidden(still takes up space in the layout).
Update acc. to the last edit of your question the event handlers don't seem to be registered anymore.
So you need:
<asp:Button ID="cmdDownload" OnClick="cmdDownload_Click" runat="server" Text="Download" />
<asp:Button ID="cmdDownloadSAP" OnClick="cmdDownload0_Click" runat="server" Text="Download SAP" />

Click page index on gridview not call to PageIndexChanging event

I have a gridview gdvNotification. When the page load first time: My gridview have paging.
My problem is:
when the page load first time: i click on the page index, but page index not changing. I debuged: when click on the page index, call to codebehide but not call to gdvNotification_PageIndexChanging event.
On browser I'm thying to use script javascript:__doPostBack('ctl00$MainContent$gdvNotification','Page$2') in console of browser, it working properly. The gdvNotification_PageIndexChanging event was called.
Here is my griview :
<asp:GridView ID="gdvNotification" runat="server" AutoGenerateColumns="False" Style="width: 100%;"
BorderWidth="0px" CellSpacing="0" CellPadding="0" GridLines="None" PageSize="1"
AllowPaging="True" ShowHeader="false" OnPageIndexChanging="gdvNotification_PageIndexChanging">
<HeaderStyle CssClass="BasicColumnTitle" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="panel1" runat="server" Width="100%" Height="618" ScrollBars="Vertical">
<table style="width: 100%;">
<tbody>
<tr style="height: 40px">
<td class="BasicValue" style="vertical-align: bottom;padding-left:2em">
<div>
<asp:Label ID="lblhead" CssClass="bold" runat="server" Text='<% #Eval("Subject")%>' Style=" font-weight: bold"></asp:Label>
</div>
</td>
</tr>
<tr style="height: 40px">
<td class=" BasicValue" style="vertical-align: bottom ;padding-left: 2em;">
<div>
<asp:Label ID="Label2" runat="server" Style=" font-weight: bold" Text='<% #Eval("AuthorName")%>'></asp:Label><asp:Label
ID="Label3" runat="server" Style="float: right" Text='<%# string.Format("{0:yyyy/MM/dd hh:mm}",Eval("BulletinDateFrom"))%>'></asp:Label></div>
</td>
</tr>
<tr style="height: 40px">
<td class="BasicValue" style="vertical-align: bottom">
<div>
<asp:Label ID="lblSection" runat="server" Style="padding-left: 2em;" Text='<%# GetSectionName(Eval("Id").ToString())%>'></asp:Label>
</div>
</tr>
<tr style="height: 497px;">
<td class="BasicValue" style="text-align: left; vertical-align: top; padding-left:2em ">
<asp:Label ID="lblContent" runat="server"
Text='<% #Eval("Contents")%>'></asp:Label>
</td>
</tr>
</tbody>
</table>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Page load method:
protected void Page_Load(object sender, EventArgs e)
{
logger.Debug("Handle event page load.");
if (!IsPostBack)
{
try
{
MasterDataHelper.RefreshCacheHeadLine();
//Get time display from system parameter
logger.Debug("Get limit new data display list.");
IList<SystemParamEntity> limitNewDataDisplayList = MasterDataHelper.GetSystemParamEntityByKbn(limitDataKBN);
IList<decimal> limitNewDataDisplayList1 =
(from item in limitNewDataDisplayList where item.DelFlg == false select item.Param1).ToList();
if (!limitNewDataDisplayList1.Any())
{
string msg = string.Format(Messages.I00010, "新規表示期間");
logger.Error(msg);
}
else
{
limitNewDataDisplay = limitNewDataDisplayList1[0];
this.hdflimitNewDataDisplay.Value = limitNewDataDisplay.ToString();
}
//Get data from session and cache
GetDataFromSessionAndCache();
//TODO: check business input datetime.now
var searchresult = ProcessFuzzySearch(DateTime.Now, SessionUtil.GetFromSession<string>(SESSION_FUZZYSEARCH));
txtFuzzySearch.Text = SessionUtil.GetFromSession<string>(SESSION_FUZZYSEARCH);
lblDate.Text = string.Format("{0}年{1}月{2}日({3})", DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day,
GetDayOfWeek((int)DateTime.Now.DayOfWeek));
pnPageIndex.Visible = false;
grvHeadline.DataSource = searchresult;
grvHeadline.DataBind();
if (searchresult.Count > 0)
{
string notificationIdSelected = searchresult[0].Id;
hdfNotificationIdSelected.Value = searchresult[0].Id;
HeadlineSelected(notificationIdSelected, 0);
grvHeadline.SelectRow(0);
}
else
{
//if: notification.count=0 => disable button edit notification
btnEditNotification.Enabled = false;
ClearDataAndDisplayForGridNotification();
}
}
catch (ApplicationException ex)
{
logger.Error(ex);
}
//Check permission for button add new head line and update notification
checkPermission();
}
}
}
Bind data for gridview grvNotification method:
private void HeadlineSelected(string notificationIdSelected, int index)
{
logger.Debug("Head line selected");
GetDataFromSessionAndCache();
IList<InformationEntity> infoNotificationList = new List<InformationEntity>();
if (string.IsNullOrEmpty(notificationIdSelected))
{
//Clear
ClearDataAndDisplayForGridNotification();
btnEditNotification.Enabled = false;
}
else
{
infoNotificationList = MasterDataHelper.GetInformationByHighOrderId(notificationIdSelected);
logger.Debug("Notification list not null");
if (infoNotificationList != null)
{
if (infoNotificationList.Count == 0)
{
pnPageIndex.Visible = false;
hdfNotificationId.Value = string.Empty;
btnEditNotification.Enabled = false;
}
else
{
if (infoNotificationList.Count == 1)
{
fakepanel.Visible = true;
}
else
{
fakepanel.Visible = false;
}
if (base.IsPermission(PERMISSION_INFORMATION_FOLLOWUP))
{
btnEditNotification.Enabled = true;
}
pnPageIndex.Visible = true;
gdvNotification.PageIndex = index;
hdfNotificationId.Value = infoNotificationList[index].Id;
gdvNotification.DataSource = infoNotificationList;
gdvNotification.DataBind();
}
logger.Debug("Set value for label total page");
lblTotalPage.Text = gdvNotification.PageCount.ToString(CultureInfo.InvariantCulture);
lbPageIndex.Text = gdvNotification.PageCount == 0
? gdvNotification.PageCount.ToString(CultureInfo.InvariantCulture)
: (gdvNotification.PageIndex + 1).ToString(CultureInfo.InvariantCulture);
lbTotal.Text = infoNotificationList.Count().ToString(CultureInfo.InvariantCulture);
}
}
}
Event pageindex changing of gridview gdvNotification:
protected void gdvNotification_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
logger.Debug("Gridview Headline page index changing .");
//gdvNotification.PageIndex = e.NewPageIndex;
HeadlineSelected(hdfNotificationIdSelected.Value, e.NewPageIndex);
//gdvNotification.DataBind();
lbPageIndex.Text = (e.NewPageIndex + 1).ToString(CultureInfo.InvariantCulture);
}
What is happening?
" call to codebehide but not call to gdvNotification_PageIndexChanging event."
If you are getting a postback but the the function isn't being called, maybe something in the Page_Load method is stopping things from happening. You aren't refilling the GridView are you? Did you forget
if (!Page.IsPostBack)

Disabled button refreshes

I Have an aspx page that contains 2 buttons "Update" and "Default". I have a dropdown list which contains a few values, say 1 to 10. When I click on Default button, the dropdown is set to a default value, say 4. If I wish to set the dropdown value to 3, I choose 3 and click on Update button and the changes are saved somewhere, maybe a DB.
Initially, Update button is disabled. Only if any changes are made to the dropdown, the Update button is enabled. Assuming that the Update button is initially disabled, I click the Default button to set the dropdown to its initial value. When I do that, a postback happens during which the Update button suddenly becomes enabled and then disabled. How do I avoid this? During page refresh, I don't want the disabled Update button to become enabled and then disabled. ALl this happens in a millisecond but its still visible.
is there any way out of this?
Design code is as follows:
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="LogSettings.aspx.cs" Inherits="Settings_LogSettings" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Diagnostic Server Configuration Tool</title>
<link rel="stylesheet" type="text/css" href="../css/style001.css" />
<style type="text/css">
a.info
{
position: relative; /*this is the key*/
z-index: 24; /*background-color:#ccc;*/
color: #000;
border-width: 0px;
border-style: none;
text-decoration: none;
}
a.info:hover
{
z-index: 25;
background-color: #ff0;
}
a.info span
{
display: none;
}
a.info:hover span
{
/*the span will display just on :hover state*/
display: block;
position: absolute;
bottom: 2em;
right: 2em;
width: 15em;
border: 1px solid #0cf;
background-color: #cff;
color: #000;
text-align: left;
padding: 5px;
}
</style>
<script language="javascript" type="text/javascript">
function setDefaults() {
if (document.getElementById("dlLoggingLevel").value != document.getElementById("dlLoggingLevel_Def").value) {
document.getElementById("dlLoggingLevel").value = document.getElementById("dlLoggingLevel_Def").value;
document.getElementById("imgLoggingLevel").src = "../images/field_ok.png";
document.getElementById("imgLoggingLevelUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
if (document.getElementById("txtMaxFileSize").value != document.getElementById("txtMaxFileSize_Def").value) {
document.getElementById("txtMaxFileSize").value = document.getElementById("txtMaxFileSize_Def").value;
document.getElementById("imgMaxSize").src = "../images/field_ok.png";
document.getElementById("imgMaxSizeUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript" type="text/javascript" src="../Css/wcf_validate.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<div class="divEditHeader" id="EditHeader">
<h1>
Logging Configuration
</h1>
<table width="100%">
<tr>
<td align="left">
<asp:Button CssClass="formEditBtn" runat="server" ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click"
Enabled="false" />
<button class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">
Default</button>
</td>
<td align="right">
</td>
</tr>
</table>
</div>
<br />
<table class="InputTable">
<tr class="Prompt">
<td class="Prompt">
Logging Level
</td>
<td>
<asp:DropDownList runat="server" ID="dlLoggingLevel">
<asp:ListItem Text="NONE" Value="none"></asp:ListItem>
<asp:ListItem Text="FATAL" Value="fatal"></asp:ListItem>
<asp:ListItem Text="ERROR" Value="error"></asp:ListItem>
<asp:ListItem Text="WARNING" Value="warning"></asp:ListItem>
<asp:ListItem Text="INFO" Value="info"></asp:ListItem>
<asp:ListItem Text="DEBUGLOW" Value="debuglow"></asp:ListItem>
<asp:ListItem Text="DEBUGMEDIUM" Value="debugmedium"></asp:ListItem>
<asp:ListItem Text="DEBUGHIGH" Value="debughigh"></asp:ListItem>
<asp:ListItem Text="DEBUGALL" Value="debugall"></asp:ListItem>
</asp:DropDownList>
<img id="imgLoggingLevel" src="../images/blank.png" />
<asp:TextBox runat="server" ID="dlLoggingLevel_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="dlLoggingLevel_Def" Style="display: none"></asp:TextBox>
<img id="imgLoggingLevelUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../Images/restore_hov.png'" onmouseout="this.src='../Images/restore.png'"
onclick="restoreValue('dlLoggingLevel','dlLoggingLevel_Init','imgLoggingLevel','imgLoggingLevelUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the desired level of diagnostic data logging. Default: INFO.
</font></span></a>
</td>
</tr>
<tr class="Prompt">
<td class="Prompt">
Maximum Log File Size(MB)
</td>
<td>
<asp:TextBox runat="server" ID="txtMaxFileSize" Width="36px" MaxLength="3"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Def" Style="display: none"></asp:TextBox>
<img id="imgMaxSize" src="../images/blank.png" />
<asp:CustomValidator runat="server" ID="valMaxSize" ControlToValidate="txtMaxFileSize"
Display="Dynamic" ErrorMessage="" ClientValidationFunction="MaxSize_Validate"></asp:CustomValidator>
<img id="imgMaxSizeUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../images/restore_hov.png'" onmouseout="this.src='../images/restore.png'"
onclick="restoreValue('txtMaxFileSize','txtMaxFileSize_Init','imgMaxSize','imgMaxSizeUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the maximum log file size in MB. Default: 2 MB. Range: 1
- 100 MB. </font></span></a>
</td>
</tr>
</table>
<br />
<asp:Label runat="server" ID="lblMessage" Font-Bold="true"></asp:Label>
<br />
</div>
</form>
</body>
</html>
Code-Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DiagnosticCommon;
using System.Drawing;
public partial class Settings_LogSettings : System.Web.UI.Page
{
const string EnvVariable = "DIAGNOSTICSERVER";
const string ConfigFileName = "DiagnosticService.exe.config";
protected void Page_Load(object sender, EventArgs e)
{
if (Security.EnforceSecurity())
Response.Redirect("Login.aspx");
if (!IsPostBack)
{
DebugHelper.MaxDebugLevel = DebugHelper.Parse(ConfigReader.GetValue("LoggingLevel"));
DebugHelper.MaxLogFileSize = long.Parse(ConfigReader.GetValue("LogFileSize"));
txtMaxFileSize.Attributes.Add("onchange", "javascript:MaxSize_Validate('',this);");
txtMaxFileSize.Attributes.Add("onkeypress", "return isNumberKey(event)");
dlLoggingLevel.Attributes.Add("onchange", "javascript:Logging_Validate('',this);");
BindData();
BindInitData();
BindDefaults();
}
}
private void BindData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel.SelectedValue = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
private void BindInitData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel_Init.Text = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize_Init.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
lblMessage.Text = "";
ConfigReader.SetValue("LoggingLevel", dlLoggingLevel.SelectedValue);
ConfigReader.SetValue("LogFileSize", txtMaxFileSize.Text);
lblMessage.Text = "Configuration updated.";
lblMessage.ForeColor = Color.Green;
btnUpdate.Enabled = false;
BindInitData();
}
catch (Exception ex)
{
lblMessage.Text += ex.Message;
lblMessage.ForeColor = Color.Red;
}
}
private void BindDefaults()
{
try
{
dlLoggingLevel_Def.Text = ConfigReader.GetDefault("LoggingLevel");
txtMaxFileSize_Def.Text = ConfigReader.GetDefault("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
btnUpdate.Enabled = false;
}
}
}
Since the button has no type defined, the default type is used which is a submit button.
This means that when you click the Default button, the JS code is running but then the form is submitted.
To avoid the submission simply make the button be ordinary button:
<button type="button" class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">Default</button>
Following is the line in setDefaults() method that enables the update button for a while, a post back occurs and update button again disabled.
document.getElementById("btnUpdate").disabled = false;
Either comment this line or set it to true

Categories