11,570 questions
You need to do ButtonWasClicked?.Invoke();
The following project is a good example of working with delegates/events between forms.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
When the user clicks on BtnAdd_Click() in FormB then the image displays in the PictureBox in FormA will move to the next image incrementImage().
I want to check whether the BtnAdd_Click() was clicked in FormB and passed to FormA to perform the incrementImage() function. The code that I tried below and gives an error Object reference not set to an instance of an object.
What I have tried:
FormA. cs
private FormB formB;
public FormA()
{
formB = new FormB();
formB.ButtonWasClicked += new FormB.ClickButton(formB_ButtonWasClicked);
}
void formB_ButtonWasClicked()
{
incrementImage();
}
public void incrementImage()
{
nCurrentItem++;
firstImage++;
if (nCurrentItem > nTotalNumber)
nCurrentItem = nTotalNumber;
else if (nCurrentItem < nTotalNumber)
{
Image img;
using (var bmpTemp = new Bitmap(ImageFileNames[nCurrentItem]))
{
img = new Bitmap(bmpTemp);
}
PicBox.Image = img;
}
else if (nCurrentItem == nTotalNumber)
{
label5.Visible = true;
endOfSession();
}
imgCounter.Text = firstImage.ToString() + " / " + nTotalNumber.ToString();
}
FormB. cs
public delegate void ClickButton();
public event ClickButton ButtonWasClicked;
private void BtnAdd_Click(object sender, EventArgs e)
{
if (listBoxFailCategories.SelectedIndex == -1)
{
MessageBox.Show("Please select any defect category");
}
else
{
var tempDefectCategory = "";
foreach (string item in listBoxFailCategories.SelectedItems)
{
string defectFolder = Path.Combine(Value, item);
File.Copy(Image, Path.Combine(defectFolder, Path.GetFileName(Image)), true);
added = true;
tempDefectCategory = tempDefectCategory + item.ToString() + ",";
FullPathName = Path.Combine(defectFolder, Path.GetFileName(Image));
}
DefectCategory = tempDefectCategory;
File.Delete(Image);
ButtonWasClicked(); //error here
this.Close();
}
}
You need to do ButtonWasClicked?.Invoke();
The following project is a good example of working with delegates/events between forms.