3

I'm new to C# programming. I've written a program in C# which has been connected to a SQL Server database through LINQ connector. Everything ran smoothly. But now I get below error when I want to delete a record from program with a specific condition:

An unhandled exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll

Additional information: Value cannot be null.

This is my C# code:

private void btnDel_Click(object sender, EventArgs e)  
{
    DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (result == DialogResult.Yes)
    {
        string photo = txtPhoto.ToString();

        var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
        db.tblPersons.Remove(edit);
        db.SaveChanges();

        MessageBox.Show("Info deleted");
    }
}

Does anyone know about my issue in this occasion?

2
  • 2
    I suspect that you need to check how the txtPhoto field is getting populated. It looks like maybe photo is an invalid value, which is causing edit to be null, and entity framework cannot remove a null value from tblPersons. Commented May 29, 2019 at 20:22
  • 1
    edit is null, obviously. Find out why + check for null. Commented May 29, 2019 at 21:38

2 Answers 2

1

I believe that control is a textbox, however, get the text.

example:

string photo = txtPhoto.Text;
Sign up to request clarification or add additional context in comments.

1 Comment

The .ToString() is not neccessary. Should be just var photo = txtPhoto.Text;
0

You should check if your var edit is not null before try to remove

private void btnDel_Click(object sender, EventArgs e)   {
        DialogResult result = MessageBox.Show("Sales system ", "Are you sure to delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            string photo = txtPhoto.ToString();

            var edit = db.tblPersons.Where(c => c.PhotoNo == photo || c.ReceiptNo == photo).FirstOrDefault();
            if(edit != null)
            {
              db.tblPersons.Remove(edit);
              db.SaveChanges();
              MessageBox.Show("Info deleted");
            }
            else
            {
             MessageBox.Show(photo + " Incorrect");
            }
        }
    }

1 Comment

This will stop the error from throwing, but it will not solve the issue of why the variable txtPhoto has an invalid value which is likely the root cause of the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.