9 Replies - 2005 Views - Last Post: 23 May 2011 - 09:44 AM Rate Topic: -----

#1 endif  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-May 11

C# Serialize ListView, Factor my code.

Posted 18 May 2011 - 11:25 AM

Im trying to build little video collection for the movies and other video files i have on my computer. I am using C# and Visual Studio 2010. My code is not very organized because I am just exploring what I can do and use. I am now trying to Serialize my listview to store it. I have tried to use the info from msdn abour XmlSerialization. I think I need to Factor my code down to few classes instead of have all my code in Form1.cs. I have no idea how i can factor this code so i can easily serialize my listview data and store it on my computer.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Xml.Serialization;

namespace ListViewNameSpace
{
    public partial class Form1 : Form
    {
        private System.ComponentModel.Container components;
        private Button addButton;
        private System.Windows.Forms.ListView listView1;
        private ListViewColumnSorter lvwColumnSorter;
        string path = @"C:\Temp\listviewfile.xml";
       
        public Form1()
        {
            InitializeComponent();
            
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;

            InitializeListView();
           
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.listView1 = new System.Windows.Forms.ListView();
            this.addButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // listView1
            // 
            this.listView1.ForeColor = System.Drawing.SystemColors.WindowText;
            this.listView1.FullRowSelect = true;
            this.listView1.GridLines = true;
            this.listView1.Location = new System.Drawing.Point(12, 12);
            this.listView1.Name = "listView1";
            this.listView1.Size = new System.Drawing.Size(480, 168);
            this.listView1.TabIndex = 0;
            this.listView1.UseCompatibleStateImagebehavior = false;
            this.listView1.LabelEdit = true;
            this.listView1.View = System.Windows.Forms.View.Details;
            this.listView1.DoubleClick += new EventHandler(listView1_DoubleClick);

            // 
            // addButton
            // 
            this.addButton.Location = new System.Drawing.Point(406, 197);
            this.addButton.Name = "addButton";
            this.addButton.Size = new System.Drawing.Size(75, 23);
            this.addButton.TabIndex = 1;
            this.addButton.Text = "Add";
            this.addButton.UseVisualStyleBackColor = true;
            this.addButton.Click += new System.EventHandler(this.addButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(503, 232);
            this.Controls.Add(this.addButton);
            this.Controls.Add(this.listView1);
            this.KeyPreview = true;
            this.Name = "Form1";
            this.Text = "Test";
            this.ResumeLayout(false);

        }

        
        protected void addButton_Click(object sender, System.EventArgs e)
        {
            string [] arr = new string[15];
            OpenFileDialog MyDialog = new OpenFileDialog();

            MyDialog.Multiselect = true ;
            MyDialog.Filter = "AVI files (*.avi*)|*.avi*|MKV files (*.mkv*)|*.mkv*|All files (*.*)|*.*";
            MyDialog.RestoreDirectory = true ;
            MyDialog.Title = "Add Files";
           
            DialogResult result = MyDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                int n = 0;
                foreach (string fName in MyDialog.FileNames)
                {
                    // Might be bad way to to this but it works. 
                    arr[n++] = Path.GetFileNameWithoutExtension(fName);
                    arr[n++] = Path.GetExtension(fName);
                    arr[n++] = GetSize(fName);
                    arr[n++] = VideoLength(fName);
                    arr[n++] = GetQuality(fName);
                    arr[n++] = SubtitleInfo(fName);
                    arr[n] = Path.GetFullPath(fName);
                 
                    ListViewItem lvi = new ListViewItem(arr);
                    listView1.Items.Add(lvi);
                    
                    n = 0;
                }
               
            }
        }

        private static string GetSize(string filename)
        {
            MovieFileDetails mfd = new MovieFileDetails(filename);
            return mfd.FileSize;
        }

        private string VideoLength (string filename)
        {
            MovieFileDetails mfd = new MovieFileDetails(filename);
            return mfd.Runtime;
        }

        private string GetQuality(string filename)
        {
            string file = Path.GetFileNameWithoutExtension(filename);
            string dvdrip = "dvdrip";
            string blur1080 = "1080p";
            string blur720 = "720p";
            string blurip = "brrip";
            string r5 = "r5";

            if ((file.ToUpper()).Contains((dvdrip.ToUpper()))) return "DVDRip";
            if ((file.ToUpper()).Contains((blurip.ToUpper()))) return "BRRip";
            if ((file.ToUpper()).Contains((blur1080.ToUpper()))) return "BluRay 1080p";
            if ((file.ToUpper()).Contains((blur720.ToUpper()))) return "BluRay 720p";
            if ((file.ToUpper()).Contains((r5.ToUpper()))) return "DVDScreener R5";
            else return "Unknown";
            
        }

        private string SubtitleInfo(string filename)
        {
            string dirname = Path.GetDirectoryName(filename);
            string fname = Path.GetFileNameWithoutExtension(filename);
            fname = dirname + "/" + fname + ".srt";
            if (File.Exists(fname))
                return "Yes";
            else
                return "No";
        }

        public void InitializeListView()
        {
            ColumnHeader header1 = this.listView1.Columns.Add("Filename", 20 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header2 = this.listView1.Columns.Add("Format", 10 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header3 = this.listView1.Columns.Add("Size", 9 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header4 = this.listView1.Columns.Add("Length", 10 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header5 = this.listView1.Columns.Add("Quality", 10 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header6 = this.listView1.Columns.Add("Subtitle", 10 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
            ColumnHeader header7 = this.listView1.Columns.Add("Path", 10 * Convert.ToInt32(listView1.Font.SizeInPoints), HorizontalAlignment.Center);
        }

       

        private void listView1_DoubleClick(object sender, EventArgs e)
        {

            string fullpath = listView1.SelectedItems[0].SubItems[6].Text;

            if (listView1.SelectedItems.Count == 1)
            {
                Console.WriteLine("Video file opened");
                try
                {
                    Process.Start(fullpath);
                }
                catch (Exception t)
                {
                    Console.WriteLine("Failed");
                }
            }
        }
            
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        /// 
        [STAThread]
        public static void Main(string[] args)
        {
            Application.Run(new Form1());
        }

    }
}


Please ask if you dont understand what i am talking about. Not an experienced programmer( and my English could be bad)

Would be great if someone could hint me how it is best to factor Form1.cs into few other classes to make it easier to serialize my listview.

Is This A Good Question/Topic? 0
  • +

Replies To: C# Serialize ListView, Factor my code.

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5437
  • View blog
  • Posts: 11,667
  • Joined: 02-June 10

Re: C# Serialize ListView, Factor my code.

Posted 18 May 2011 - 12:22 PM

 I have tried to use the info from msdn abour XmlSerialization.


Where? I don't see any method for serialization. Maybe I missed it.

You said you read the MSDN about serialization.
So you must have read that you cannot serialize GUI controls, right?
So you can't serialize a ListView control.

You serialize objects and collections of objects.

I would suggest you make a class of "VideoEntry" and then you can have a List<VideoEntry> that is the datasource for your ListView.

When you de/serialize, you de/serialize the List<>

When you've tried that much and actually have some serialization code to share, please just continue with this thread. There is no need to start a new thread for the same issue.
Was This Post Helpful? 2
  • +
  • -

#3 endif  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-May 11

Re: C# Serialize ListView, Factor my code.

Posted 18 May 2011 - 12:35 PM

View PosttlhIn`toq, on 18 May 2011 - 12:22 PM, said:

 I have tried to use the info from msdn abour XmlSerialization.


Where? I don't see any method for serialization. Maybe I missed it.

You said you read the MSDN about serialization.
So you must have read that you cannot serialize GUI controls, right?
So you can't serialize a ListView control.

You serialize objects and collections of objects.

I would suggest you make a class of "VideoEntry" and then you can have a List<VideoEntry> that is the datasource for your ListView.

When you de/serialize, you de/serialize the List<>

When you've tried that much and actually have some serialization code to share, please just continue with this thread. There is no need to start a new thread for the same issue.


Sorry i took them out because they didnt work and at first i was trying to Serialize the ListView. Maybe stupid question but i dont see it. What whould i have in that "VideoEntry" class? And Would it be right to do it like this in the addButton_Click , after i have put my elements in arr[], List<VideoEntry> movielist = new List<VideoEntry>(arr); ?
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5437
  • View blog
  • Posts: 11,667
  • Joined: 02-June 10

Re: C# Serialize ListView, Factor my code.

Posted 18 May 2011 - 12:49 PM

A VideoEntry would be the class-objects you are trying to store.

A VideoEntry would have properties like:
  • Title
  • Director
  • Year
  • Length
  • Subtitles
  • Quality


Quote

And Would it be right to do it like this in the addButton_Click , after i have put my elements in arr[], List<VideoEntry> movielist = new List<VideoEntry>(arr); ?


You wouldn't put your elements into an array at all.
You would have a List<VideoEntry> to store all of your VideoEntry instances.
When you make a new VideEntry, set all of the properties, then add it to the List
Was This Post Helpful? 1
  • +
  • -

#5 endif  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-May 11

Re: C# Serialize ListView, Factor my code.

Posted 19 May 2011 - 07:13 AM

Am I going in right direction with this.

Made this Class1.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ListViewNameSpace
{
    class Class1
    {
        string filename;

        public Class1(string filename)
        {
            this.filename = filename;
        }
       
        public string GetFilename()
        {
            return Path.GetFileNameWithoutExtension(filename);
        }

        public string GetFormat()
        {
            return Path.GetExtension(filename);
        }

        public string GetSize()
        {
            MovieFileDetails mfd = new MovieFileDetails(filename);
            return mfd.FileSize;
        }

        public string Runtime()
        {
            MovieFileDetails mfd = new MovieFileDetails(filename);
            return mfd.Runtime;
        }

        public string GetQuality()
        {
            string file = Path.GetFileNameWithoutExtension(filename);
            string dvdrip = "dvdrip";
            string blur1080 = "1080p";
            string blur720 = "720p";
            string blurip = "brrip";
            string r5 = "r5";

            if ((file.ToUpper()).Contains((dvdrip.ToUpper()))) return "DVDRip";
            if ((file.ToUpper()).Contains((blurip.ToUpper()))) return "BRRip";
            if ((file.ToUpper()).Contains((blur1080.ToUpper()))) return "BluRay 1080p";
            if ((file.ToUpper()).Contains((blur720.ToUpper()))) return "BluRay 720p";
            if ((file.ToUpper()).Contains((r5.ToUpper()))) return "DVDScreener R5";
            else return "Unknown";

        }

        public string SubtitleInfo()
        {
            string dirname = Path.GetDirectoryName(filename);
            string fname = Path.GetFileNameWithoutExtension(filename);
            fname = dirname + "/" + fname + ".srt";
            if (File.Exists(fname))
                return "Yes";
            else
                return "No";
        }

        public string GetFullPath()
        {
            return Path.GetFullPath(filename);
        }
    }
}



And have my addButton_Click method in Form1.cs like this now:
  protected void addButton_Click(object sender, System.EventArgs e)
        {
            string [] arr = new string[15];
            OpenFileDialog MyDialog = new OpenFileDialog();

            MyDialog.Multiselect = true ;
            MyDialog.Filter = "AVI files (*.avi*)|*.avi*|MKV files (*.mkv*)|*.mkv*|All files (*.*)|*.*";
            MyDialog.RestoreDirectory = true ;
            MyDialog.Title = "Add Files";
            
           
            DialogResult result = MyDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                int n = 0;
                foreach (string fName in MyDialog.FileNames)
                {
                   
                    movielist.Add(new Class1(fName));

                }
                UpdateListView();
            }
        }
 private void UpdateListView()
        {
            foreach (Class1 list in movielist)
            {
                ListViewItem item = new ListViewItem();
                item.Text = list.GetFilename();
                item.SubItems.Add(list.GetFormat());
                item.SubItems.Add(list.GetSize());
                item.SubItems.Add(list.Runtime());
                item.SubItems.Add(list.GetQuality());
                item.SubItems.Add(list.SubtitleInfo());
                item.SubItems.Add(list.GetFullPath());
                listView1.Items.Add(item);
            }
        }




This seems to work fine, but every time I add a file to the list the whole list is wrote again plus the new ones. It is, all the files that are already in the ListView wrote again. How could i solve that and can I know serialize that List?
Was This Post Helpful? 0
  • +
  • -

#6 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6039
  • View blog
  • Posts: 23,436
  • Joined: 23-August 08

Re: C# Serialize ListView, Factor my code.

Posted 19 May 2011 - 07:25 AM

Wouldn't you like to clear the contents of the ListView before you update it?
Was This Post Helpful? 1
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5437
  • View blog
  • Posts: 11,667
  • Joined: 02-June 10

Re: C# Serialize ListView, Factor my code.

Posted 19 May 2011 - 08:42 AM

Like many new coders you share a bad habit that you need to get out of...
Stop using the GUI controls to hold your values.

We see it with things like string values. People don't make a property for "SavePath" - they just retreive the txtSavePath.Text from a textbox.

You're doing the same thing with your collection. You haven't made a proper collection for your Class1 instances. You're just shoving them into the ListView

Without a collection how will you traverse all of them? How can you search all of them for just the DVD quality videos?

Take a look at post #2 again. You need to make a collection such as a List<Class1> or a Class1[].

Then you can set the .DataSource of your ListView to the collection. Doing that means you won't have to manually frak with adding and subtracting to the list programmatically.
Was This Post Helpful? 3
  • +
  • -

#8 endif  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-May 11

Re: C# Serialize ListView, Factor my code.

Posted 22 May 2011 - 06:20 PM

Have something like that know.

Movie.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace MovieCollection
{
    [Serializable]
    public class Movie
    {
        [XmlElement]
        public string Filename{ get; set; }

        [XmlElement]
        public string Format { get; set; }

        [XmlElement]
        public string FileSize { get; set; }

        [XmlElement]
        public string Runtime { get; set; }

        [XmlElement]
        public string Quality { get; set; }

        [XmlElement]
        public string Subtitle { get; set; }

        [XmlElement]
        public string Path { get; set; }
    }
}



Library.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace MovieCollection
{
    [Serializable]
    public class Library
    {
        [XmlElement]
        public List<Movie> Movies { get; set; }
    }
}



and LibraryManager.cs

using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;


namespace MovieCollection
{
    public class LibraryManager
    {
        public Library Library { get; set; }

        public void Save()
        {
            /*using (XmlWriter xWriter = XmlWriter.Create(ConfigurationSettings.AppSettings["SaveLocation"]))
            {
                XmlSerializer xSer = new XmlSerializer(typeof(Library));
                xSer.Serialize(xWriter, Library);
            }*/

            XmlSerializer serializer = new XmlSerializer(typeof(Library));
            Stream stream = new FileStream(@"C:\Temp\filelist.xml", FileMode.OpenOrCreate);
            serializer.Serialize(stream, Library);
            stream.Close();
        }

        public void Load()
        {
            /*using (XmlReader xReader = XmlReader.Create(ConfigurationSettings.AppSettings["SaveLocation"]))
            {
                XmlSerializer xSer = new XmlSerializer(typeof(Library));
                Library = (Library)xSer.Deserialize(xReader);
            }*/

            XmlSerializer serializer = new XmlSerializer(typeof(Library));
            Stream reader = new FileStream(@"C:\Temp\filelist.xml", FileMode.Open);
            Library = (Library)serializer.Deserialize(reader);
            reader.Close();

        }

        public void AddMovie(string title, string format, string size, string runtime, 
                                                string qual, string subinfo, string path )
        {

            Library.Movies.Add(
                new Movie()
                {
                    Filename = title,
                    Format = format,
                    FileSize = size,
                    Runtime = runtime,
                    Quality = qual,
                    Subtitle = subinfo,
                    Path = path

                });
        }
        public void AddMovie(Movie movie)
        {
            Library.Movies.Add(movie);
        }

        public void DeleteMovie(string filename, bool exactMatch = false, bool onlyFirstMatch = true)
        {
            if (exactMatch)
            {
                var movie = Library.Movies.Where(m => m.Filename.Equals(filename)).Single();
                Library.Movies.Remove(movie);
                return;
            }
            var movies = Library.Movies.Where(m => m.Filename.Contains(filename));
            if (onlyFirstMatch)
            {
                var first = movies.First();
                Library.Movies.Remove(first);
                return;
            }
            movies.ToList().ForEach(m => Library.Movies.Remove(m));
        }
    }
}


These are all in the project MovieCollection.

In the project(under same solution) MyMovieCollection is Form1.cs

using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieCollection;

namespace MyMovieCollection
{
    public partial class Form1 : Form
    {
        private Container components;
        private Button addButton;
        private DataGridView filelist;
        private LibraryManager librarymanager;
 
        public Form1()
        {
            InitializeComponent();
            librarymanager = new LibraryManager();
            if (File.Exists(@"C:\Temp\filelist.xml"))
            {
                librarymanager.Load();
            }
            else librarymanager.Library = new Library() { Movies = new List<Movie>() };
            this.filelist.DataSource = librarymanager.Library.Movies;
        }

        #region Initialize Components
        private void InitializeComponent()
        {
            this.filelist = new System.Windows.Forms.DataGridView();
            this.addButton = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.filelist)).BeginInit();
            this.SuspendLayout();
            // 
            // filelist
            // 
            this.filelist.AllowUserToAddRows = false;
            this.filelist.AllowUserToOrderColumns = true;
            this.filelist.GridColor = System.Drawing.SystemColors.ControlLight;
            this.filelist.Location = new System.Drawing.Point(168, 23);
            this.filelist.Name = "filelist";
            this.filelist.ReadOnly = true;
            this.filelist.Size = new System.Drawing.Size(695, 200);
            this.filelist.TabIndex = 0;
            // 
            // addButton
            // 
            this.addButton.Location = new System.Drawing.Point(788, 241);
            this.addButton.Name = "addButton";
            this.addButton.Size = new System.Drawing.Size(75, 23);
            this.addButton.TabIndex = 1;
            this.addButton.Text = "Add";
            this.addButton.UseVisualStyleBackColor = true;
            this.addButton.Click += new System.EventHandler(this.addButton_Click);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(887, 445);
            this.Controls.Add(this.filelist);
            this.Controls.Add(this.addButton);
            this.KeyPreview = true;
            this.Name = "Form1";
            this.Text = "Test";
            ((System.ComponentModel.ISupportInitialize)(this.filelist)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

       
        // Add new videofile or files to filelist
        protected void addButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog MyDialog = new OpenFileDialog();
            MyDialog.Multiselect = true;
            MyDialog.Filter = "AVI files (*.avi*)|*.avi*|MKV files (*.mkv*)|*.mkv*|All files (*.*)|*.*";
            MyDialog.RestoreDirectory = true;
            MyDialog.Title = "Add Files";

            DialogResult result = MyDialog.ShowDialog();
            if (result == DialogResult.OK)
            {

                foreach (string fName in MyDialog.FileNames)
                {
                    Movie m = new Movie();
                    m.Filename = "Batman";
                    m.Format = ".mkv";
                    m.FileSize = "6,4 GB";
                    m.Runtime = "1:20:00";
                    m.Subtitle = "yes";
                    m.Path = "Temp";

                    librarymanager.AddMovie(m);
                }
            }
            UpdateMovieListBox();
        }

        private void UpdateMovieListBox()
        {
            this.SuspendLayout();
            filelist.Invalidate();
            filelist.DataSource = null;
            filelist.DataSource = librarymanager.Library.Movies;
            this.Update();
        }
    }
}



I switched to DataGridView, think it fitts better for this program. But every time i run the program i get my window and click add button and select some videofile. I get a row with the info i set in the foreach loop in addbutton_Click but when i Click on the row or columnheader in the DataGridWView i get this error message.

"Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click quit, the application will close immediately.

Index -1 does not have a value."

If i click Details button i get these information.
See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.IndexOutOfRangeException: Index -1 does not have a value.
   at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
   at System.Windows.Forms.CurrencyManager.get_Current()
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
   at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
   at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
   at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
   at System.Windows.Forms.DataGridView.onmousedown(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.DataGridView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativewindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativewindow.WndProc(Message& m)
   at System.Windows.Forms.Nativewindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)



Can someone tell me what is wrong with the code or what is causing this exception or error?

This post has been edited by endif: 22 May 2011 - 06:22 PM

Was This Post Helpful? 0
  • +
  • -

#9 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5437
  • View blog
  • Posts: 11,667
  • Joined: 02-June 10

Re: C# Serialize ListView, Factor my code.

Posted 23 May 2011 - 05:34 AM

Collections (arrays and List<>s for example) have elements.
These are zero-indexed, meaning the first element is index 0, second element is index 1 and so on.

Controls such as DataGridView, ComboBox, ListBox and so on that as their SelectedIndex report -1 when nothing is selected, 0 for the first element, 1 for the second element and so on. If the .SelectedIndex equals -1 then nothing is selected.

On to the error, it should be a little more clear.
You are getting the SelectedIndex of -1 from the DataGridView and trying to process it as the index to your collection. But there is no such thing as element -1 of a collection.


Debugging tutorial
Debugging tips
Great debugging tips
It still doesn't work, article

This post has been edited by tlhIn`toq: 23 May 2011 - 05:35 AM

Was This Post Helpful? 0
  • +
  • -

#10 endif  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 18-May 11

Re: C# Serialize ListView, Factor my code.

Posted 23 May 2011 - 09:44 AM

Solved the problem by change my List< > to BindingList< > Everything works perfect know. Thanks for the help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1