Reputation: 15
First of all, I would like to point out that I am quite a beginner in C#.
My code is:
private static void addImageToPanel(imageData[] images, Panel panel)
{
Panel imagePanel;
PictureBox imageImage;
Label imageLabel;
Size imageSize = new()
{
Width = 80,
Height = 80,
};
Size imagePanelSize = new()
{
Width = 100,
Height = 100,
};
const int posX = 60;
const int posY = 140;
foreach (imageData image in images)
{
if (!panel.Controls.ContainsKey(image.key))
{
imagePanel = new()
{
Name = image.key,
Size = imagePanelSize,
Left = posX * x + margin,
Top = posY * y + margin,
Cursor = Cursors.Hand,
};
//Error here VVV toolStripClick (CS0120: An object reference is required for the non-static field, method, or property 'member')
imagePanel.Click += new EventHandler(toolStripClick);
imageLabel = new()
{
Name = image.key + "_text",
Text = image.name,
ForeColor = Color.White,
Font = new Font("Segoe UI", 8),
Dock = DockStyle.Bottom,
TextAlign = ContentAlignment.MiddleCenter,
};
imageImage = new()
{
Name = image.key + "_image",
Image = Image.FromFile("C:\\..."),
SizeMode = PictureBoxSizeMode.Zoom,
Size = fileSize,
Dock = DockStyle.Top,
};
panel.Controls.Add(imagePanel);
imagePanel.Controls.Add(imageLabel);
imagePanel.Controls.Add(imageImage);
}
}
}
where "toolStripClick" is:
private void toolStripClick(object sender, EventArgs e)
{
contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}
I can't understand why this doesn't work. Adding static to "toolStripClick" doesn't help.
Even tried to do a for loop after adding all the images, like this:
for (int i = 0; i < mainPanel.Controls.Count; i++)
{
mainPanel.Controls[i].Click += new EventHandler(toolStripClick);
}
It doesn't display any errors other than a warning (CS8622: Nullability ref...), but it still doesn't work.
Edit: Nevermind I just found that deleting static from "addImageToPanel" fix it, partially as it do not work on panel, but work on label...
Is there a way to make it work on panel? Or any workaround?
Edit2: Replaced "focusPanel" to "imagePanel". (My mistake while copy pasting. It was and is imagePanel not focusPanel.)
Upvotes: 0
Views: 53
Reputation: 15
Changing
private static void addImageToPanel(imageData[] images, Panel panel)
to
private void addImageToPanel(imageData[] images, Panel panel)
and
imagePanel.Click += new EventHandler(toolStripClick);
to
imageImage.Click += new EventHandler(toolStripClick);
imageLabel.Click += new EventHandler(toolStripClick);
fix it partialy.
Probably I'm already going outside of this thread problem, but how I can get info which image I clicked to remove or edit it?
Upvotes: 0