I want to save full path of listbox in C#

Kailash Sahu 141 Reputation points
2021-07-22T17:33:01.757+00:00

First Of All I add Directory in Listbox, Like A Directory, B Directory. When User Click the item of ListBox ,Get the full path of Items in C#
Someone modify the code !
Thanks in Advance !

BindingSource listboxsource = null;
public Form1()
{
InitializeComponent();
listboxsource = new BindingSource(Properties.Settings.Default.listboxitems, "");
someListbox.DataSource = listboxsource;

}

//Add Folder in Listbox
private void button57_Click(object sender, EventArgs e)
{

FolderBrowserDialog dialog = new FolderBrowserDialog();

dialog.Description = "Please Select Folder";

if (dialog.ShowDialog() == DialogResult.OK)
{

string folderName = dialog.SelectedPath;

string s = Path.GetFileName(folderName);
listboxsource.Add(s);

Properties.Settings.Default.Save();
listboxsource = new BindingSource(Properties.Settings.Default.listboxitems, "");
someListbox.DataSource = listboxsource;
}
}

private void listBox5_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string fullname = Properties.Settings.Default.FullName;

Properties.Settings.Default.Save();
MessageBox.Show(fullname);
}
catch(Exception)
{ }
}

117201-sds.jpg

C#
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.
10,938 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,421 Reputation points
    2021-07-22T22:28:43.323+00:00

    I would highly suggest storing information in a json file rather than under settings.

    Full source

    117233-filelistbox.png

    Using NewtonSoft NuGet package

    public static class JsonHelpers  
    {  
        public static string FileName = "Items.json";  
      
        /// <summary>  
        /// Create a mockup if file does not exists  
        /// </summary>  
        public static void InitializeData()  
        {  
            if (!File.Exists(FileName))  
            {  
                File.WriteAllText(JsonHelpers.FileName, JsonConvert.SerializeObject(MockOperations.List, Formatting.Indented));  
            }  
        }  
      
        /// <summary>  
        /// Read items  
        /// </summary>  
        /// <returns></returns>  
        public static List<FileItem> Read() =>   
            JsonConvert.DeserializeObject<List<FileItem>>(File.ReadAllText(JsonHelpers.FileName));  
      
        /// <summary>  
        /// Save items  
        /// </summary>  
        /// <param name="list"></param>  
        public static void Save(List<FileItem> list) =>   
            File.WriteAllText(FileName, JsonConvert.SerializeObject(list, Formatting.Indented));  
    }  
      
    

    Container class

    public class FileItem : INotifyPropertyChanged  
    {  
        private string _fullName;  
      
        public string FullName  
        {  
            get => _fullName;  
            set  
            {  
                _fullName = value;  
                OnPropertyChanged();  
            }  
        }  
      
        [JsonIgnore]  
        public string FileName => Path.GetFileName(FullName);  
        public override string ToString() => FileName;  
        public event PropertyChangedEventHandler PropertyChanged;  
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        }  
    }  
    

    Form code

    public partial class Form1 : Form  
    {  
        public BindingSource _BindingSource = new BindingSource();  
        public Form1()  
        {  
            InitializeComponent();  
              
            JsonHelpers.InitializeData();  
              
            _BindingSource.DataSource = JsonHelpers.Read();  
              
            listBox1.DataSource = _BindingSource;  
              
            listBox1.MouseDoubleClick += ListBox1OnMouseDoubleClick;  
              
            Closing += OnClosing;  
        }  
      
        private void OnClosing(object sender, CancelEventArgs e)  
        {  
            JsonHelpers.Save((List<FileItem>)_BindingSource.DataSource);  
        }  
      
        private void ListBox1OnMouseDoubleClick(object sender, MouseEventArgs e)  
        {  
            if (_BindingSource.Current == null) return;  
              
            if (!label1.Visible)  
            {  
                label1.Visible = true;  
            }  
      
            label1.Text = ((FileItem) _BindingSource.Current).FullName;  
      
        }  
      
        private void AddNewButton_Click(object sender, EventArgs e)  
        {  
            _BindingSource.Add(new FileItem() {FullName = "D:\\Docs\\readme.md"});  
        }  
    }  
    

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,591 Reputation points
    2021-07-23T02:21:04.027+00:00

    It is rare to store information in this location, but maybe you have your reasons, so I will modify it based on the current code.

    You did not show the code in Properties.Settings. Based on the current information, I guess it looks like this:

        internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase  
        {  
      
            private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));  
            public List<string> listboxitems = new List<string>();  
            public string FullName { get; set; }  
            public static Settings Default  
            {  
                get  
                {  
                    return defaultInstance;  
                }  
            }  
        }  
    

    The listboxitems has nothing to do with FullName. You add elements to listboxitems in the code, but FullName is always empty.

    Since those items are directories, then we can use DirectoryInfo to store its information.

            public List<DirectoryInfo> listboxitems = new List<DirectoryInfo>();  
    

    Code in Form:

            private void button1_Click(object sender, EventArgs e)  
            {  
                FolderBrowserDialog dialog = new FolderBrowserDialog();  
      
                dialog.Description = "Please Select Folder";  
      
                if (dialog.ShowDialog() == DialogResult.OK)  
                {  
               
                    string folderName = dialog.SelectedPath;  
                    DirectoryInfo directoryInfo = new DirectoryInfo(folderName);  
      
                    Properties.Settings.Default.listboxitems.Add(directoryInfo);  
      
                    Properties.Settings.Default.Save();  
                    listboxsource = new BindingSource(Properties.Settings.Default.listboxitems.Select(d=>d.Name), "");  
                    listBox1.DataSource = listboxsource;  
                }  
            }  
      
            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)  
            {  
                try  
                {  
                    ListBox listBox = sender as ListBox;  
                    string fullname = Properties.Settings.Default.listboxitems[listBox.SelectedIndex].FullName;  
      
                    Properties.Settings.Default.Save();  
                    MessageBox.Show(fullname);  
                }  
                catch (Exception ex)  
                {  
                    //do something  
                }  
            }  
    

    In the SelectedIndexChanged method, please don't use try-catch but do nothing in the catch. If there is an exception in the code in the try, the application will have no prompt, so please add some code in the catch to handle the exception.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

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