C# WinForm求助:两个PictureBox加载数据库不同图片却显示相同
Hey there! Let's get your two PictureBoxes showing the correct distinct images from your picture and picturem database fields. The issue you're seeing (both showing the same image) usually boils down to one of a few easy-to-fix problems—let's walk through solutions step by step.
First: Verify Your Database Data
Before touching code, rule out the simplest cause: are the picture and picturem fields in your database actually storing different images?
- Run a query directly on your database to check the binary data (e.g.,
SELECT picture, picturem FROM your_table WHERE ...). Compare the byte lengths of the two fields—if they're identical, the problem is in your database, not your code.
Fix Your Code
Your current code is missing key checks and proper resource management. Here's a revised, robust version that ensures each PictureBox gets the correct image:
// Assume 'dr' is your SqlDataReader (or other DbDataReader) if (dr.HasRows) { **Critical:** Make sure you're reading the correct row from the DataReader dr.Read(); // Load image for Picture (from 'picture' field) if (dr["picture"] != DBNull.Value) { byte[] imgBytes = (byte[])dr["picture"]; // Use 'using' to auto-dispose the MemoryStream (prevents memory leaks) using (MemoryStream ms = new MemoryStream(imgBytes)) { Picture.Image = Image.FromStream(ms); } Picture.Refresh(); } else { // Set to null if the field is empty Picture.Image = null; } // Load image for PictureMadani (from 'picturem' field) if (dr["picturem"] != DBNull.Value) { byte[] imgmBytes = (byte[])dr["picturem"]; using (MemoryStream msm = new MemoryStream(imgmBytes)) { PictureMadani.Image = Image.FromStream(msm); } PictureMadani.Refresh(); } else { PictureMadani.Image = null; } }
Common Mistakes to Check For
- Forgot to call
dr.Read(): If your DataReader isn't positioned on a valid row, it might return default/duplicate values for both fields. Always calldr.Read()after checkingdr.HasRows. - Typos in field names: Double-check that
dr["picturem"]matches exactly the column name in your database (case sensitivity depends on your database setup). - Unchecked DBNull: If either field is empty, casting directly to
byte[]will throw an error—our code adds a check forDBNull.Valueto avoid this. - Reusing the same stream/image: Your original code creates separate streams, but if you accidentally reused an Image object elsewhere, that could cause duplicate displays. The revised code ensures each PictureBox gets a fresh Image instance.
Debugging Tip
Add quick checks to confirm you're reading different data:
// Insert this after reading the byte arrays Console.WriteLine($"Picture byte length: {imgBytes.Length}"); Console.WriteLine($"PictureMadani byte length: {imgmBytes.Length}");
If the lengths are different, your code should work once you fix any DataReader issues. If they're the same, go back to verifying your database data.
内容的提问来源于stack exchange,提问作者Bukhalifa

