I'm developing a small POS for a university project. I have a form which acts as a POS main window, with a datagrid and so on. Also, I have one form who is the Sensitive search or Incremental search, and I want that form to, select one item in a listbox and return it to the main window. Now I have a property in the main which gets that item as a string, and when the user clicks the OK button on the search form, I want to set that property on the main window.
Everything works great except one thing: when I try to access listBox_Codigo.SelectedItem.ToString();
the app tries to dispose and closes all windows...
Does anybody know why?
I just need the selected string in that listbox and set it to the main window like this:
var Principal = (PDQ.Cajero)this.ParentForm;
Principal.CodigoInsertado = listBox_Codigo.SelectedItem.ToString();
this.DialogResult = DialogResult.OK;
this.Close();
where PDQ.Cajero
is the main form, which calls this form.
UPDATE: I just finished debugging it, and right after the program gets to
listBox_Codigo.SelectedItem.ToString();
the program jumps to Dispose()
.
UPDATE 2 This is my complete method:
private void button1_Click(object sender, EventArgs e)
{
if (listBox_Codigo.SelectedItem == null)
{
if (MessageBox.Show(this, "No se puede ingresar un producto sin seleccionarlo.\n ¿Desea intentarlo de nuevo, o Salir?", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
{
DialogResult = DialogResult.Cancel;
this.Close();
}
}
else
{
var Principal = (PDQ.Cajero)this.ParentForm;
Principal.CodigoInsertado = listBox_Codigo.SelectedItem.ToString();
this.DialogResult = DialogResult.OK;
this.Close();
}
}
So the problem is not if the value is null...
There likely is no SelectedItem
(meaning that the value of the property is null
). In this case your code is throwing a NullReferenceException
, since you can't call a function on a null
reference. Because you aren't catching it, the application is catching it at a higher level an attempting to exit. This is what's calling your Dispose
method.