简体   繁体   中英

Disable a button on page load with a specific ID

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM