I have multiples buttons on my asp.net page, I need to disable certain button(s) on page load.
Which button will be disabled is determined by my database, which I successfully retrieved.
For example, I have retrieved the ID "B01", and in my page there's a button's ID named "B01"
I have to disable this button on page load, how do I do it?
Just do - if(!IsPostBack){id.Enabled = false;} on page load and make sure button must be like <asp:Button ID="btn_dn" runat="server" >Button</asp:Button> button need runat="server"
As you are using simple button so it will not take any c# command so you have to use asp button or javascript to disable button
for simple button <input type="button" disabled="disabled" value="B01" /> Or
<button id="B01" runat="server" disabled="disabled">B01</button>
You can do this in Page_Load event
string id="B01";
(FindControl(id) as Button).Enabled = false;
There are challenges with FindControl and "nested" controls. I believe you need a recursive find control function have a look at the tutorial.
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
then call it using
var x = FindControlRecursive(this.Master,"ButtonName") as Button;
x.Visible = false or x.Enabled = false
Tutorial Link is here....
in page load:
string id = "A01";
var q = from R in db.Reservations
where R.Flight_NO == id
select R.Seat;
foreach (var item in q)
{
Button b = (Button)this.Master.FindControl("main").FindControl(item);
if (b!=null)
{
b.Enabled = false;
}
}
this does automatically disable button with that specific ID on page load
Related
I am generating x amount of buttons and I give all of them a unique name.
After all those are generated, I want to edit one of them without regenerating them so I was wondering if I could get a component by its name?
I am using WinForms
Yes:
Control myControl = Controls.Find("textBox1");
Now, beware that you have to do proper casting hen found, because Find returns a control.
You can use Controls property of your form (or some container control on your form). With LINQ you can select buttons and then find first button with required name:
var button1 = Controls.OfType<Button>().FirstOrDefault(b => b.Name == "button1");
Or if you want to search child controls recursively
var button1 = Controls.Find("button1", true)
.OfType<Button>()
.FirstOrDefault();
Without LINQ you can use method Find(string key, bool searchAllChildren) of ControlCollection:
Control[] controls = Controls.Find("button1", true);
if (controls.Length > 0)
{
Button button1 = controls[0] as Button;
}
Button btn1 = (Button)(Controls.Find("btnName"));
This will get the required button and will save the button attributes into a new Button btn1
After all those are generated, I want to edit one of them without
regenerating them so I was wondering if I could get a component by its
name?
var myButton = Controls.Find("buttonName", true).FirstOrDefault(); //Gets control by name
if(myButton != null)
{
if (myButton.GetType() == typeof(Button)) //Check if selected control is of type Button
{
//Edit button here...
}
else
{
//Control isn't a button
}
}
else
{
//Control not found.
}
Make sure you add a reference to: linq.
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
In asp.net (c#) how can I find out which asp:button triggered the postback?
I am using it for dynamic controls and want to do a different process on pageload for different buttons. I have tried looking at __EVENTARGUMENTS etc. but they didnt work.
I am looking to do something like this:
Page_load
Case:
Button 1 clicked
//Do something
Button 2 clicked
//Do something
Use the below code.
public static string GetPostBackControlId(this Page page)
{
if (!page.IsPostBack)
return string.Empty;
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
Calling this function:
I have included the above function in a static class UtilityClass.
String postBackControlId = UtilityClass.GetPostBackControlId(this);
The code has been referenced from Mahesh's Blog.
We are using Sharepoint 2007 In which on master page we have Asp Image button. We want to set this image button as default button for enter key press. We tried some ways but not getting success.
Turned out more complicated than I thought but possible nonetheless. First of all, make sure the ID of your control is static:
<asp:ImageButton runat="server" ID="MyImageButton" ClientIDMode="Static" ImageUrl="pic.gif" OnClick="ImageButtonClicked" />
Now what you need is the following JavaScript code in your .aspx or .master page:
<script type="text/javascript">
var DEFAULT_BUTTON_ID = "MyImageButton";
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// A fallback to window.onload, that will always work
window.addEventListener("load", HandleDefaultButton, false);
// If IE event model is used
} else if (document.attachEvent) {
// A fallback to window.onload, that will always work
window.attachEvent("onload", HandleDefaultButton);
}
function HandleDefaultButton() {
var inputs = document.getElementsByTagName("input");
//attach event for all inputs
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
//maybe already got handler so add instead of override
if (document.addEventListener)
input.addEventListener("keypress", InputElement_KeyPressed, false);
else if (document.attachEvent)
input.attachEvent("onkeypress", InputElement_KeyPressed);
}
}
function InputElement_KeyPressed(evt) {
if (DEFAULT_BUTTON_ID && DEFAULT_BUTTON_ID.length > 0) {
//old IE event module
if (typeof evt == "undefined" || !evt)
evt = window.event;
var keyCode = evt.keyCode || evt.which;
if (keyCode === 13) {
var oButton = document.getElementById(DEFAULT_BUTTON_ID);
if (oButton) {
oButton.click();
return false;
} else {
alert("---DEBUG--- default button is defined but does not exist (" + DEFAULT_BUTTON_ID + ")");
}
}
}
return true;
}
</script>
You just need to define the real ID as the value of DEFAULT_BUTTON_ID and the code will automatically attach keypress event to all inputs (text, checkbox and radio) and when Enter is pressed, the button defined as default will get clicked.
As you're using SharePoint is means window.onload is already in use so we must add our own event not override it.
You can set the DefaultButton property to the id of the button you want to be default in the form tag.
I have a login control and at is nested 2 deep in a header control
i.e Page --> Header Control --> Login Control. I cannot get a reference to the control on the page using FindControl. I want to be able to set the visible property of the control like
if (_loginControl != null)
_loginControl.Visible = false;
I ended up using a recursive FindControl method to find the nested control.
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Are you needing to disable/hide the User Control from the ASP.NET page it resides on (or does the User Control exist on a master page, say)? If it's in the same page, then in your ASP.NET page's code-behind you'd do:
MyUserControlsID.Visible = false
Where MyUserControl is the ID of your User Control. To determine the ID of your User Control look at the markup of your .aspx page and you will see something like this:
<uc1:UserControlName ID="MyUserControlsID" runat="server" ... />
Happy Programming!
A good way would be to use:
Page.FindControl()
if that yields null, the control is not there.
Try calling this.FindControl("_loginControl") or this.Page.FindControl("_loginControl").
See MSDN for method details:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx
The login control, if it's registered in the markup, will also be an instance member of your codebehind page; you can refer to it from the codebehind class as if it were a normal member, using the same name you provided as the ID (I do recommend using codebehinds for most logic, instead of inlining code in the markup, BTW).
You can also use the FindControl() method of your page, which will search its control subtree for a control with a given ID. That takes longer, so I would recommend the first option unless the logic control is added dynamically and you don't always know it's there.
private List<Control> GetAllNestedUserControl(Control ph)
{
List<Control> Get = new List<Control>();
foreach (var control in ph.Controls)
{
if (control is UserControl)
{
UserControl uc = control as UserControl;
if (uc.HasControls())
{
Get = GetAllNestedUserControl(uc);
}
}
else
{
Control c = (Control)control;
if (!(control is LiteralControl))
{
Get.Add(c);
}
}
}
return Get;
}
just call this code from you any parent page and then get any control by the following code
List<Control> Get = GetAllNestedUserControl(ph);
Label l = (Label)Get.Find(o => o.ID == "lblusername");
l.Text = "changed from master";