button event accidentally occured after textchanged - c#

I have a problem with textchanged event on textbox.
After i input some string and hit enter, i don't know why button click is fired too
here my .aspx
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="labelKodeDivisi" runat="server" style="z-index: 1; left: 62px; top: 57px; position: absolute" Text="labelKodeDivisi"></asp:Label>
<asp:Label ID="labelNamaDivisi" runat="server" style="z-index: 1; left: 62px; top: 85px; position: absolute" Text="labelNamaDivisi"></asp:Label>
<asp:Button ID="butLogout" runat="server" OnClick="butLogout_Click" style="z-index: 1; left: 682px; top: 40px; position: absolute" Text="Button" />
<asp:TextBox ID="tbKode" runat="server" OnTextChanged="tbKode_TextChanged" style="z-index: 1; left: 71px; top: 127px; position: absolute"></asp:TextBox>
</form>
and here my aspx.cs
public partial class FormDivisi2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butLogout_Click(object sender, EventArgs e)
{
labelKodeDivisi.Text = "123";
}
protected void tbKode_TextChanged(object sender, EventArgs e)
{
labelNamaDivisi.Text = "555";
}
}
Whats going on is, when i input text in textbox tbKode and hit enter, labelNamaDivisi.text change to 555 but labelKodeDivisi.text also change to 555.
What i want is when i input some text in textbox tbKode, labelNamaDivisi.text change to 555 but labelKodeDivisi not change. labelKodeDivisi only change when i hit button butLogout

you can try this
$('input').keypress(function(event){
if(event.keyCode==13)
{
event.preventDefault();
}
})

Related

How do I refresh a web controler inside a gridview ASP.NET

How can I refresh a web controller inside a gridview? I have a web controller inside a gridview as you can see here:
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%" style="background: #F5F5F5">
<div id="div<%# Eval("contrato_id") %>" style="overflow: auto; display: none; position: relative; left: 15px; overflow: auto">
<div class="ExpandTableHeader">
</div>
<div class="body">
<div id="tabs-ComponentesSection" class="menusection">
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</div>
</ItemTemplate>
</asp:TemplateField>
I want to refresh the following controller.
<TWebControl5:WebControl5 ID="Header8" runat="server" />
On the following button click.
<asp:Button class="btn btn-primary" ID="btnChooseContract" runat="server" Text="Elegir contrato" OnClick="AddContractToQuote" />
Here is the code behind of the button.
protected void AddContractToQuote(object sender, EventArgs e)
{
}
Used some code that looks like this YEARS ago...
for (int x = 0; x < GridViewName.Rows.Count; x++)
{
GridViewRow row = (GridViewRow) GridViewName.Rows[x];
Control contr = (control) row.Cells[1].FindControl("NameOfYourControl");
contr = //Another similar control that looks like the first, but different
}

How to receive datalist item when sender is html button?

In my DataList I want a button to be displayed with a FA icon, so I used a html button and made it runat="server", now when I click the button I want to know which Datalist Item is 'bounded' with this button.
I tried to use a asp.net button, but I can't use FA icons then.
This is what my html and c# code looks like:
<asp:DataList Width="100%" ID="dtlFAQSections" runat="server" DataSourceID="dtsFAQSections" DataKeyField="FAQSectionID">
<ItemTemplate>
<h2>
<button id="btnFAQSection" runat="server" onserverclick="btnFAQSection_Click" style="background-color:#f24646; border:none; color:white; margin-left:25px; font-size:16px; cursor:pointer; height: 26px; width: 26px; margin-right: 5px; border-radius:30%;"><i class="fas fa-plus"></i></button>
<asp:Label Font-Size="18px" ID="FAQSectionNameLabel" runat="server" Text='<%# Eval("FAQSectionName") %>' />
</h2>
<hr style="border: 1px dotted #000000; border-style: none none dotted; color: #fff; background-color: #fff;"/>
</ItemTemplate>
</asp:DataList>
protected void btnFAQSection_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
DataListItem item = (DataListItem)btn.NamingContainer;
}
First, you need to use HtmlButton since you are not using an ASP control as a Button. Then simply find the Parent.
protected void btnFAQSection_Click(object sender, EventArgs e)
{
HtmlButton btn = (HtmlButton)sender;
DataListItem item = (DataListItem)btn.NamingContainer;
//now you can access the DataListItem
Label label = item.FindControl("FAQSectionNameLabel") as Label;
label.Text = "DataListItem Found";
//or if you want to get the parent DataList
DataList dl = btn.Parent.Parent as DataList;
Label1.Text = dl.ID;
}

stop alert box from firing on every postback

I have a webform that displays an alert box when a searched for item is not found. the alertbox is all asp side, calling it is c# side in codebehind.
the issue is that after the first time it is called, it calls on every postback of the page. after the click it should not fire again until after another missed search.
i have tried if(!ispostback), but the initial firing is a postback, so it won't fire at all.
during the postback it doesn't even call the c# code again, it just shows the alertbox.
<style type="text/css">
.alertBox
{
position: absolute;
top: 100px;
left: 50%;
width: 500px;
margin-left: -250px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
padding: 4px 8px;
}
</style>
<script type="text/javascript">
function closeAlert(e) {
e.preventDefault();
this.parentNode.style.display = "none";
}
</script>
</head>
<body>
<form id="form_rooftopSAQPM" runat="server">
<div runat="server" id="AlertBox" class="alertBox" Visible="false">
<div runat="server" id="AlertBoxMessage"></div>
<button onclick="closeAlert.call(this, event)">Ok</button>
</div>
...
private void site_Load(string siteNumber)
{
DataSet ds = retrieveDataFromSQL("exec s_RooftopSite " + siteNumber, "Couldn't retrieve site information");
if(ds.Tables.Count>0)
{
//load the fields
txtFoo.Text = ds.Tables[0].Rows[0][0].ToString();
}
else
{
MessageBoxShow("Site not found.");
}
}
protected void MessageBoxShow(string message)
{
this.AlertBoxMessage.InnerText = message;
this.AlertBox.Visible = true;
}
...
how can i set the alertbox to only fire when it is called by the c# code, yet still allow it to pop off on the first call, which is a postback?
I fixed it by switching from JavaScript to C#:
ASP:
<asp:Button runat="server" id="btnCloseAlert"
onclick="btnCloseAlert_Click" Text="Ok" />
CodeBehind in C#:
protected void btnCloseAlert_Click(object sender, EventArgs e)
{
AlertBox.Visible = false;
AlertBoxMessage.InnerText = "";
}

multi-tab/panel control does not always respond correctly

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

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