Why when adding from dictionary<string,string> to listBox and then selecting items in the listBox SelectedIndexChanged event there is error?

Sharon Lipman 21 Reputation points
2022-10-06T17:58:04.08+00:00

At the top form1

Dictionary<string, string> FileList = new Dictionary<string, string>();  

In the constructor

public Form1()  
        {  
            InitializeComponent();  
  
            string g = File.ReadAllText(@"d:\rectangles.txt");  
            FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);  
            listBox1.DataSource = FileList.ToList();   
        }  

in the selected index event

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)  
        {  
            pictureBox1.Image = System.Drawing.Image.FromFile(FileList  
        .Where(x => x.Key == ((ListBox)sender).SelectedItem?.ToString())  
        .Select(x => x.Value).First()  
    );  
        }  

the exception error is on the line in the selected index event when i try to select another item in the listBox :

System.InvalidOperationException HResult=0x80131509 Message=Sequence contains no elements Source=System.Core

kkcZV.jpg

Not sure if i need to use the class RectangleConverter Class and how to use it and where in the code ?

"I doubt that .SelectedItem.ToString() yields the expected result... If the dictionary key is "a" and the value is "b" then I'd expect, [a, b]"

I'm stuck with this problem.

This is the full code :

using Newtonsoft.Json;  
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Drawing.Drawing2D;  
using System.Drawing.Imaging;  
using System.IO;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
using static System.Net.Mime.MediaTypeNames;  
using static System.Net.WebRequestMethods;  
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;  
  
namespace Image_Crop  
{  
    public partial class Form1 : Form  
    {  
        System.Drawing.Image img = null;  
        Rectangle rect;  
        int pixelsCounter = 0;  
        Color SelectedColor = Color.LightGreen;  
        List<DrawingRectangle> DrawingRects = new List<DrawingRectangle>();  
        Bitmap rectImage;  
        int saveRectanglesCounter = 1;  
        bool drawBorder = true;  
        bool clearRectangles = true;  
        bool saveRectangles = true;  
        string rectangleName;  
        Dictionary<string, string> FileList = new Dictionary<string, string>();  
        JsonSerializer serializer = new JsonSerializer();  
  
        public Form1()  
        {  
            InitializeComponent();  
  
            pictureBox2.Image = System.Drawing.Image.FromFile(@"d:\Comparison\ConvertedBmp.bmp");  
             
            img = System.Drawing.Image.FromFile(@"d:\Comparison\radar_without_clouds.jpg");  
  
            checkBoxDrawBorder.Checked = true;  
            checkBoxClearRectangles.Checked = true;  
            checkBoxSaveRectangles.Checked = true;  
  
            if (System.IO.File.Exists(@"d:\rectangles.txt"))  
            {  
                string g = System.IO.File.ReadAllText(@"d:\rectangles.txt");  
                FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);  
                listBox1.DataSource = FileList.ToList();  
            }  
        }  
  
        public class DrawingRectangle  
        {  
            public Rectangle Rect => new Rectangle(Location, Size);  
            public Size Size { get; set; }  
            public Point Location { get; set; }  
            public Control Owner { get; set; }  
            public Point StartPosition { get; set; }  
            public Color DrawingcColor { get; set; } = Color.LightGreen;  
            public float PenSize { get; set; } = 3f;  
        }  
  
        private void Form1_Load(object sender, EventArgs e)  
        {  
  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            if (img == null)  
            {  
                // Create image.  
                img = System.Drawing.Image.FromFile(@"d:\Comparison\ConvertedBmp.bmp");  
            }  
        }  
  
        private void Form1_Paint(object sender, PaintEventArgs e)  
        {  
  
        }  
  
        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)  
        {  
            if (e.Button != MouseButtons.Left) return;  
            DrawingRects.Add(new DrawingRectangle()  
            {  
                Location = e.Location,  
                Size = Size.Empty,  
                StartPosition = e.Location,  
                Owner = (Control)sender,  
                DrawingcColor = SelectedColor // <= Shape's Border Color  
            });  
        }  
  
        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)  
        {  
            if (e.Button != MouseButtons.Left) return;  
  
            var dr = DrawingRects[DrawingRects.Count - 1];  
            if (e.Y < dr.StartPosition.Y) { dr.Location = new Point(dr.Rect.Location.X, e.Y); }  
            if (e.X < dr.StartPosition.X) { dr.Location = new Point(e.X, dr.Rect.Location.Y); }  
  
            dr.Size = new Size(Math.Abs(dr.StartPosition.X - e.X), Math.Abs(dr.StartPosition.Y - e.Y));  
            pictureBox2.Invalidate();  
        }  
  
        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)  
        {  
            if (e.Button != MouseButtons.Left) return;  
  
            if (DrawingRects.Count > 0)  
            {  
                // The last drawn shape  
                var dr = DrawingRects.Last();  
                if (dr.Rect.Width > 0 && dr.Rect.Height > 0)  
                {  
                    rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);  
                    if (saveRectangles)  
                    {  
                        rectangleName = @"d:\Rectangles\rectangle" + saveRectanglesCounter + ".bmp";  
                        FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);  
                        string json = JsonConvert.SerializeObject(  
    FileList,  
    Formatting.Indented // this for pretty print  
);  
                        using (StreamWriter sw = new StreamWriter(@"d:\rectangles.txt", false))  
                        {  
                            sw.Write(json);  
                            sw.Close();  
                        }  
  
  
                        rectImage.Save(rectangleName);  
                        saveRectanglesCounter++;  
                    }  
                    pixelsCounter = rect.Width * rect.Height;  
                    pictureBox1.Invalidate();  
  
                    // ListBox used to present the shape coordinates  
                    listBox1.Items.Add($"{dr.Location}, {dr.Size}");  
  
                    StreamWriter w = new StreamWriter(@"d:\Rectangles\rectangles.txt", true);  
                    w.WriteLine(rectangleName.Substring(23) + " ===> " + $"{dr.Location}, {dr.Size}");  
                    w.Close();  
                }  
            }  
        }  
  
        private void pictureBox2_Paint(object sender, PaintEventArgs e)  
        {  
            DrawShapes(e.Graphics);  
        }  
  
        private void pictureBox1_Paint(object sender, PaintEventArgs e)  
        {  
            if (drawBorder)  
            {  
                ControlPaint.DrawBorder(e.Graphics, pictureBox1.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);  
            }  
  
            if (rectImage != null && DrawingRects.Count > 0)  
            {  
                var dr = DrawingRects.Last();  
                e.Graphics.DrawImage(rectImage, dr.Rect);  
  
                if (clearRectangles)  
                {  
                    DrawingRects.Clear();  
                    pictureBox2.Invalidate();  
                }  
            }  
        }  
  
        private void DrawShapes(Graphics g)  
        {  
            if (DrawingRects.Count == 0) return;  
            g.SmoothingMode = SmoothingMode.AntiAlias;  
            foreach (var dr in DrawingRects)  
            {  
                using (Pen pen = new Pen(dr.DrawingcColor, dr.PenSize))  
                {  
                    g.DrawRectangle(pen, dr.Rect);  
                };  
            }  
        }  
  
        public Bitmap cropAtRect(Bitmap b, Rectangle r)  
        {  
            Bitmap nb = new Bitmap(r.Width, r.Height);  
            using (Graphics g = Graphics.FromImage(nb))  
            {  
                g.DrawImage(b, -r.X, -r.Y);  
                return nb;  
            }  
        }  
  
        private void checkBoxDrawBorder_CheckedChanged(object sender, EventArgs e)  
        {  
            if (checkBoxDrawBorder.Checked)  
            {  
                drawBorder = true;  
            }  
            else  
            {  
                drawBorder = false;  
            }  
  
            pictureBox1.Invalidate();  
        }  
  
        private void checkBoxClearRectangles_CheckedChanged(object sender, EventArgs e)  
        {  
            if (checkBoxClearRectangles.Checked)  
            {  
                clearRectangles = true;  
            }  
            else  
            {  
                clearRectangles = false;  
            }  
  
            pictureBox2.Invalidate();  
        }  
  
        private void checkBoxSaveRectangles_CheckedChanged(object sender, EventArgs e)  
        {  
  
        }  
  
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)  
        {  
            pictureBox1.Image = System.Drawing.Image.FromFile(FileList  
    .Where(x => x.Key == ((ListBox)sender).SelectedItem?.ToString())  
    .Select(x => x.Value).First());  
        }  
    }  
}  
Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2022-10-06T21:38:29.673+00:00

    Perform assertion using FirstOrDefault as First will as you found out throw an exception if the where condition can not be fullfilled e.g.

    var test = System.Drawing.Image.FromFile(FileList  
             .Where(x => x.Key == ((ListBox)sender).SelectedItem?.ToString())  
             .Select(x => x.Value).FirstOrDefault();  
    

    Assert test then when the where condition should work but does not breakout the code more and step through the code with breakpoints and the debugger.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.