Search code examples
c#sql-servervisual-studiovisual-studio-codeicsharpcode

System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.'


My operation work is when I click on the cells of gridview: The Records in gridview will go to the textbox and picture box.

This exception error occurs when I click on an empty cell(No records in datagridview) in the gridview.

I share picture of my operation

It comes from the error is. Here is my codes:

  private void btn_picopen_Click(object sender, EventArgs e)
    {
        /*OpenFileDialog opf = new OpenFileDialog();
        opf.Filter = "Select Pic(*.JPG;*.png;.gif)|*.jpg;*.png;*.gif";
        if (opf.ShowDialog() == DialogResult.OK)
         {
            pic_staff.Image = Image.FromFile(opf.FileName);
        }*/
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Filter = "png files(*.png)|*.png|jpg files(*.jpg)|*.jpg|All files(*.*)|*.* ";
        if(dialog.ShowDialog() == DialogResult.OK)
        {
            imglocation = dialog.FileName.ToString();
            pic_staff.ImageLocation = imglocation;
        }
        


    }
private void btn_save_Click(object sender, EventArgs e)
    {

        if (Isvalid())
        {
            byte[] images = null;
            FileStream streem = new FileStream(imglocation, FileMode.Open, FileAccess.Read);
            BinaryReader brs = new BinaryReader(streem);
            images= brs.ReadBytes((int)streem.Length);

            SqlCommand cmd = new SqlCommand("INSERT INTO Add_New_Staff VALUES(@Staff_Name, @Father_Name, @City, @Address, @Mobile_No, @E_mail, @CNIC, @Education, @Subject, @Experience, @pic, @designation)", con);  //AddEsp ki jaga store procedure ka name
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@Staff_Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Father_Name", txt_fathername.Text);
            cmd.Parameters.AddWithValue("@City", txt_city.Text);
            cmd.Parameters.AddWithValue("@Address", txt_address.Text);
            cmd.Parameters.AddWithValue("@Mobile_No", txt_mobileno.Text);
            cmd.Parameters.AddWithValue("@E_mail", txt_email.Text);
            cmd.Parameters.AddWithValue("CNIC", txt_cnic.Text);
            cmd.Parameters.AddWithValue("@Education", txt_education.Text);
            cmd.Parameters.AddWithValue("@Subject", txt_subject.Text);
            cmd.Parameters.AddWithValue("@Experience", txt_experience.Text);
            cmd.Parameters.AddWithValue("@designation", txt_designation.Text);
            cmd.Parameters.AddWithValue("@pic", images);
            cmd.Parameters.AddWithValue("@Staff_Id", this.staff_Id);


            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("New Staff has been Added", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
            GetStudentsrecord();
            Clearformat();
        }
    }
 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {

        staff_Id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value);
        txt_name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
        txt_fathername.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
        txt_city.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
        txt_address.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
        txt_mobileno.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
        txt_email.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
        txt_cnic.Text = dataGridView1.SelectedRows[0].Cells[7].Value.ToString();
        txt_education.Text = dataGridView1.SelectedRows[0].Cells[8].Value.ToString();
        txt_experience.Text = dataGridView1.SelectedRows[0].Cells[9].Value.ToString();
        txt_subject.Text = dataGridView1.SelectedRows[0].Cells[10].Value.ToString();
        txt_designation.Text = dataGridView1.SelectedRows[0].Cells[11].Value.ToString();
        // pic_staff.Image = dataGridView1.SelectedRows[0].Cells[10].Value as Image;
        byte[] bytes = (byte[])dataGridView1.SelectedRows[0].Cells[12].Value;
        MemoryStream ms = new MemoryStream(bytes);
        pic_staff.Image = Image.FromStream(ms);


    }

Solution

  • If you want to detect only one row's data, you can use datagirdview.CurrentRow property.

    You can use Convert.IsDBNull method to check if the value is DBnull.

    Here is code example may help you.

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                if ((!Convert.IsDBNull(dataGridView1.CurrentRow.Cells[1].Value)))
                {
                    byte[] bytes = (byte[])dataGridView1.CurrentRow.Cells[1].Value;
                    Image image = byteArrayToImage(bytes);
                    pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                    pictureBox1.Image = image;
                }
                else
                {
                    MessageBox.Show("there is no image in the row, please click aonther row");
                }
            }
    
           
            //convert bytearray to image
            public Image byteArrayToImage(byte[] byteArrayIn)
            {
                using (MemoryStream mStream = new MemoryStream(byteArrayIn))
                {
                    return Image.FromStream(mStream);
                }
            }
    

    Result:

    enter image description here