ホイールを使用して、フォームが読み込まれるたびに (たとえば) 30 個のボタンの背景画像を変更したいと考えています。
私はこれを使用できません:
for(int i=1;i<=30;i++)
{
button i .backgroundimage=image.fromfile("URL");
}
私は何をすべきか?
あなたの問題には多くの可能な解釈があります。コードを使用できないのはなぜですか? あなたの問題にはさまざまな解決策もあります。
例として:
public Form1() // Constructor
{
InitializeComponent(); // Ensure all controls are created.
List<Button> buttons = new List<Button>(30);
buttons.Add(mybutton1)
buttons.Add(mybutton2)
// Go futher with all your buttons.
}
private void Form1_Load(object sender, System.EventArgs e) // Create a load event
{
foreach(Button button in buttons)
{
button.BackgroundImage = Image.FromFile(path);
// Note: The file remains locked until the Image is disposed!
}
}
このコードが Form_Load で実行され、ボタンの親コントロールがフォームであると仮定すると、このようなものを使用できます。背景画像として設定したい画像への実際のパスを提供する必要があることに注意してください
string path = "rootNameOfTheImage";
int counter = 0;
foreach(Control ctrl in this.Controls)
{
if(ctrl is Button)
{
Button btn = (Button)ctrl;
if(/* test if this button should be used */)
{
btn.BackgroundImage=Image.FromFile(path + counter++.ToString() + ".jpg");
}
}
}