Reputation:
I just created ten buttons and last two buttons named btn_green and btn_red,.
I wanna to change all button color to the green and red when click those buttons green and red.
My C# code is
protected void btn_green_Click(object sender, EventArgs e)
{
foreach (Button btn in this.Controls)
{
btn.BackColor = Color.DarkGreen;
}
}
protected void btn_red_Click(object sender, EventArgs e)
{
foreach (Button btn in this.Controls)
{
btn.BackColor = Color.Red;
}
}
but my bed luck i got only error
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'ASP.site_master' to type 'System.Web.UI.WebControls.Button'.
Line 20: foreach (Button btn in this.Controls)
how i escape this problem?.
Upvotes: 3
Views: 2786
Reputation: 39329
The 'foreach' doesn't filter the controls to return all buttons. Rather it loops through all controls and tries to cast them to Button. That fails if it's not a button.
Plus (and that may not be a problem in your case) this.Controls
will only return Controls directly under 'this' and not nested inside some container. If you also want controls at a deeper lever, you will need a recursive function.
If you don't need recursion, you can use Linq:
foreach(Button btn in Controls.OfType<Button>())
{
btn.BackColor = Color.Red;
}
Upvotes: 1
Reputation: 197
You need to check the type of control before using it as a button since Form.Control returns all controls in the form.
Try following code block
foreach (Control objControl in this.Controls)
{
if (objControl is Button)
{
(objControl as Button).BackColor = Color.DarkGreen;
}
}
Upvotes: 0
Reputation: 1036
foreach (Button btn in this.Controls)
returns all control in your page, not just your buttons. You need to cast it to button or try its type before accessing it.
foreach (Control control in Controls)
{
var btn = control as Button;
if (btn != null)
{
...
}
}
Upvotes: 1