Winform image image shows empty c #

I have a form containing a picture. When the form loads the default image, the image stops. Then I update the image when something in my form changes, which changes the displayed image. Generating this image also works great, I see the image on disk and open it with paint, etc. In general, what I do is open the file stream at the image location, and then set the image to this location.

 if (this.picPreview.Image != null)
 {
    this.picPreview.Image.Dispose();
    this.picPreview.Image = null;
 }
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
this.picPreview.Image = System.Drawing.Image.FromStream(fs);

But no matter what I do, the image looks blank on the form. I tried updating the form by updating the image control, setting the visible property to visible, nothing helps.

I create a separate form that contains only the image and transfers the location of the image to the form and repeats the process of opening the stream, and then sets the image to this place where it works fine.

AFAIK throws no exceptions ... the debugger is set to break in all exceptions.

What can cause this behavior?

Any advice is appreciated. I have another application that creates an image in a background worker thread, and this works fine.

, , , . datagridview , . . . SelectionChanged. . , , . . , . , , , datagrid.

, . , , , , , , . , , , , . , , , , . . , , .

.

. :

, datagrid, SQL. Dgv , . , . , comboboxes checkboxes . . , , . . , , .

, , . , . . , ; , , , .

, dgv selectchanged. , . btnSave_Click, selectedchanged , , . , , , , ( ), "" . , . , .

: enter image description here

selectionchanged btn_save:

/// <summary>
        /// update the preview on a row selection change
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (!BindingComplete) return;

            DataGridView dgv = (DataGridView)sender;

            if (!dgv.Focused || dgv.CurrentRow == null) return;         

            // set the pic preview to the current row image(s)
            // we need the record for the current index
            DataRowView currentDataRowView = (DataRowView)dgv.CurrentRow.DataBoundItem;

            if (currentDataRowView == null) return;

            DataRow currentRow = currentDataRowView.Row;

            LastSelectedIndex = dgv.SelectedRows[0].Index;

            Debug.WriteLine("Current row in SelectionChanged: " + currentRow.ItemArray[0].ToString());

            bool showBox = false, showProd = false, showWire = false;
            string box, prod, wire;

            string pdcProductName = currentRow.ItemArray[0].ToString();

            showWire = !string.IsNullOrEmpty(wire = currentRow.ItemArray[7].ToString());

            showBox = !string.IsNullOrEmpty(box = currentRow.ItemArray[8].ToString());

            showProd = !string.IsNullOrEmpty(prod = currentRow.ItemArray[9].ToString());

            // check for wirepath, box, and product. Enable the nav buttons if there is more than 
            // one label for this product. We need to check for LabelFileName being the same for both
            // box and product, in which case there is one file for both which defaults to box
            if ((showBox && showProd && prod == box) || showBox)
            {
                string targetFile = PreviewImagePath + pdcProductName + "_eBox.png";

                if (picPreview.Image != null)
                {
                    //picPreview.Image.Dispose();
                    //picPreview.Image = null;
                }

                // if the preview image doesn't exist yet use a default image
                if (!File.Exists(targetFile))
                {
                    // make the loading gif invisible
                    this.picLoading.Visible = true;

                    //picPreview.Image = AdminTILE.Properties.Resources.StandardPaper;
                }
                else
                {
                    this.picLoading.Visible = false;
                    Debug.WriteLine("Opening file " + targetFile);

                    FileStream fs = new FileStream(targetFile, FileMode.Open, FileAccess.Read);
                    picPreview.Image = System.Drawing.Image.FromStream(fs);
                    Image imgCopy = (Image)picPreview.Image.Clone();
                    this.picPreview.Visible = true;
                    fs.Close();

                    // preview in another frame
                    if (frm.IsDisposed)
                    {
                        frm = new PreviewImage();
                    }
                    frm.PreviewLabel(imgCopy);
                    frm.Show();                 

                    //picPreview.ImageLocation = targetFile;
                }
            }            
            else if (showProd)
            {
                string targetFile = PreviewImagePath + pdcProductName + "_eBox.png";

                if (picPreview.Image != null)
                {
                    picPreview.Image.Dispose();
                    //picPreview.Image = null;
                }

                if (!File.Exists(targetFile))
                {
                    // make the loading gif invisible
                    this.picLoading.Visible = true;
                    //picPreview.Image = AdminTILE.Properties.Resources.StandardPaper;
                }
                else
                {
                    this.picLoading.Visible = false;
                    FileStream fs = new FileStream(targetFile, FileMode.Open, FileAccess.Read);
                    picPreview.Image = System.Drawing.Image.FromStream(fs);
                    fs.Close();
                }
            }           

        }


        /// <summary>
        /// update the database with the current selections
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {

            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("No record is selected to update");
                return;
            }

            DialogResult result1 = MessageBox.Show("Saving Label Configuration. Are you sure?",
                "IMPORTANT!", MessageBoxButtons.YesNoCancel);

            // update the view
            if (result1 == DialogResult.Yes)
            {

                // we need the record for the current index
                DataRowView currentDataRowView = (DataRowView)dataGridView1.CurrentRow.DataBoundItem;
                DataRow currentRow = currentDataRowView.Row;                
                string pdcProductName = currentRow.ItemArray[0].ToString();



                Int32 currentIndex = dataGridView1.SelectedRows[0].Index;

                Debug.WriteLine("Current index in Save:" + currentIndex.ToString());

                string AgencyId="", LogoId="", WireId="";

                SqlDataAdapter LabeledProductsDataTableAdapter =
                new SqlDataAdapter("SELECT * FROM LabeledProducts",
                    printConfigTableAdapter.Connection);

                SqlDataAdapter LogosDataTableAdapter =
                new SqlDataAdapter("SELECT * FROM Logos",
                    printConfigTableAdapter.Connection);

                if (vwTILEAdminTableAdapter.Connection.State != ConnectionState.Open)
                {
                    printConfigTableAdapter.Connection.Open();
                }

                DataTable LogoDataTable = new DataTable();
                LogosDataTableAdapter.Fill(LogoDataTable);

                DataTable LabeledProductsDataTable = new DataTable();
                LabeledProductsDataTableAdapter.Fill(LabeledProductsDataTable);

                StringBuilder sql = new StringBuilder();

                // Fill a table with the results of the 
                // data adapter and query the table instead of the database.
                // An empty LogoDescription maps to an empty filename
                DataRow dataRow;

                if (cbAgency.SelectedItem != null)
                {
                    sql.Append("LogoDescription = '").Append(cbAgency.SelectedItem).Append("'");                       
                    dataRow = LogoDataTable.Select(sql.ToString())[0];
                    AgencyId = dataRow.ItemArray[0].ToString();

                    sql.Clear();
                }

                if (cbPrivateLabel.SelectedItem != null)
                {
                    sql.Append("LogoDescription = '").Append(cbPrivateLabel.SelectedItem).Append("'");
                    dataRow = LogoDataTable.Select(sql.ToString())[0];
                    LogoId = dataRow.ItemArray[0].ToString();

                    sql.Clear();
                }

                if (cbWire.SelectedItem != null)
                {

                    sql.Append("LogoDescription = '").Append(cbWire.SelectedItem).Append("'");
                    dataRow = LogoDataTable.Select(sql.ToString())[0];
                    WireId = dataRow.ItemArray[0].ToString();

                    sql.Clear();
                }


                // PdcProductName is the primary key
                sql.Append(@"UPDATE [dbo].[LabeledProducts]
                    SET [PdcProductName] = @pdcProd
                        ,[LabelProductName] = @lblProd
                        ,[LabelDescription] = @lblDesc
                        ,[Power] = @pwr
                        ,[Fabrication] = 0
                        ,[UL_File_Number] = @ul
                        ,[PrePrintedSerial] = @pps
                        ,[ShowOrderOnLabel] = 0
                        ,[PrivateLabelLogoId] = @plid
                        ,[AgencyImageId] = @aid
                        ,[WireDiagConfigId] = @wid
                        ,[ReleasedForProduction] = @rfp
                    WHERE PdcProductName = '").Append(pdcProductName).Append("'");

                using (SqlCommand command = new SqlCommand(sql.ToString(), vwTILEAdminTableAdapter.Connection))
                {
                    if (vwTILEAdminTableAdapter.Connection.State != ConnectionState.Open)
                        vwTILEAdminTableAdapter.Connection.Open();

                    LabeledProductsDataTableAdapter.UpdateCommand = command;
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@pdcProd", txtPdcProdName.Text);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@lblProd", txtLabeledProd.Text);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@lblDesc", txtLabelDesc.Text);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@pwr", txtPower.Text);                       
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@ul", txtULFileNumber.Text);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@pps", cbPrePrintedSerial.Checked);

                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@plid", LogoId);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@aid", AgencyId);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@wid", WireId);
                    LabeledProductsDataTableAdapter.UpdateCommand.Parameters.AddWithValue("@rfp", cbReleased.Checked);

                    //int rowsAffected = LabeledProductsDataTableAdapter.Update(LabeledProductsDataTable);  
                    int rowsAffected = command.ExecuteNonQuery();

                    // The DataViewManager returned by the DefaultViewManager
                    // property allows you to create custom settings for each
                    // DataTable in the DataSet.
                    DataViewManager dsView = this.tILEDataSet.DefaultViewManager;

                    // remove the selectionChanged event handler during updates
                    // every update causes this handler to fire three times!!!
                    this.dataGridView1.SelectionChanged -= new System.EventHandler(this.dataGridView1_SelectionChanged);


                    dataGridView1.DataSource = typeof(TILEDataSet.vwTILEAdminDataTable);
                    this.vwTILEAdminBindingSource.DataSource = typeof(TILEDataSet.vwTILEAdminDataTable);
                    this.vwTILEAdminBindingSource.DataSource = this.tILEDataSet.vwTILEAdmin;
                    this.dataGridView1.DataSource = this.vwTILEAdminBindingSource;                     
                    vwTILEAdminBindingSource.ResetBindings(false); // false for data change, true for schema change

                    this.vwTILEAdminTableAdapter.Fill(this.tILEDataSet.vwTILEAdmin);

                    // we need to reget the row after the update to pass to preview
                    currentIndex = LastSelectedIndex;
                    DataGridViewRow drv = this.dataGridView1.Rows[currentIndex];
                    currentRow = ((DataRowView)(drv.DataBoundItem)).Row;

                    // update the preview files

                    UpdatePreviewFiles(currentRow);


                    // try this
                    dataGridView1.ClearSelection();
                    // this doesn't work
                    dataGridView1.Rows[currentIndex].Selected = true;


                    // reset the selection changed handler once the update is complete
                    this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);

                }

            }
        }

, , , , .

Aftersave

UpdatePreviewFiles . ShowPreview picturebox.Image. , /.

- , , , , , .

.

+5
1

:

this.picPreview.Image = Image.FromFile(imagePath);

, FileStream.

, this.picPreview.Image null . dispose, , .

null - , () - , GC (Garbage Collector) .

Dispose GC , . ( Rowland Shaw), Image.FromFile(imagePath) .

, GC , ( , ).

, , WHOLE .

+4
source

All Articles