如何在文本文件中保存列表框 [英] How can I save a listbox in a text file

查看:106
本文介绍了如何在文本文件中保存列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好!

我怀疑,我搜索了很多但没有发现任何东西,我希望有人可以帮助我。

非常好。



我有2个表格,在Form1上我有一个按钮,在Form2中我有一个带有数据的ListBox。

我想要的是点击按钮Form1并将Form2 ListBox中的数据保存在文本文件中。



列表框中的数据类型相当简单,列表框最多有12行,并且每行只有一个单词。



我尝试过:



这是Form1上的按钮



 private void toolStripButtonGuardar_Click(object sender,EventArgs e)
{
var myForm = new FormVer();

// Escolher onde salvar o arquivo
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
sfd.Title =Guardar;
sfd.Filter =Arquivos TXT(* .txt)| * .txt;

if(sfd.ShowDialog()== DialogResult.OK)
{
try
{

File.WriteAllLines(sfd。 FileName,myForm.listBox.Items.OfType< string>());

// Mensagemdeconfirmçç
MessageBox.Show(Guardado com sucesso,Notificação,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,Erro,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}





但它不起作用,始终将文件保存为空白。

解决方案

 File.WriteAllText(sfd.FileName, string 。加入(  |,myForm.listBox.Items.OfType< string>())); 



更新:以上解决方案基于所提供的信息。你暗示列表中的数据是简单的字符串,所以上面的代码连接字符串并将它们作为连续字符串写入磁盘。



如果你使用复杂的对象就像类一样,那么你需要做更多的工作来序列化对象,然后才能将它写入磁盘。



这是一个[Newtonsoft] JSON助手,用于序列化和反序列化:

 使用 Newtonsoft.Json; 
使用 System.Collections.Generic;

命名空间 DotNet.Shared.Helpers
{
public static class JsonConverter
{
public static string FromClass< T>(T数据, bool isEmptyToNull = false ,JsonSerializerSettings jsonSettings = null
{
string response = string .Empty;

if (!EqualityComparer< T> .Default.Equals(data, default (T)))
response = JsonConvert.SerializeObject(data,jsonSettings);

return isEmptyToNull? (response == {} null:response):response;
}

public static T ToClass< T>(< span class =code-keyword> string data,JsonSerializerSettings jsonSettings = null
{
var response = default (T);

if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject< T>(data)
:JsonConvert.DeserializeObject< T>(data,jsonSettings);

return 响应;
}
}
}



使用:

 File.WriteAllText(sfd.FileName,JsonConverter.FromClass(listBox1.Items.OfType< Person>())); 





更新#2:由于以下行,您将始终拥有空白文件:

  var  myForm =  new  FormVer(); 



您需要使用空数据创建新表单指向带有数据的活动表单。类似于:

  var  myForm = Application.OpenForms [ nameof (FormVer)]; 


Good morning!
I have a doubt, I searched a lot but found nothing, I hope someone can help me.
Very well.

I have 2 Forms, on Form1 I have a button and in the Form2 I have a ListBox with data.
What I want is to click the button on Form1 and save the data from the Form2 ListBox in a text file.

The data types that are in the listbox are fairly straightforward, the listbox has at most 12 line, and each row has only one word.

What I have tried:

This is button on Form1

private void toolStripButtonGuardar_Click(object sender, EventArgs e)
        {
            var myForm = new FormVer();

            //Escolher onde salvar o arquivo
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.Title = "Guardar";
            sfd.Filter = "Arquivos TXT (*.txt)|*.txt";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    File.WriteAllLines(sfd.FileName, myForm.listBox.Items.OfType<string>());

                    //Mensagem de confirmação
                    MessageBox.Show("Guardado com sucesso", "Notificação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }



But it doesn't work, always save the file blank.

解决方案

File.WriteAllText(sfd.FileName, string.Join("|", myForm.listBox.Items.OfType<string>()));


Update: The above solution is based on the information provided. You imply that the data in the list are simple strings, So the above code joins strings and writes them to disk as a continuous string.

If you are using complex objects like classes, then you need to do more work to serialize the object before you can write it to disk.

Here is a [Newtonsoft] JSON helper for serializing and deserializing:

using Newtonsoft.Json;
using System.Collections.Generic;

namespace DotNet.Shared.Helpers
{
    public static class JsonConverter
    {
        public static string FromClass<T>(T data, bool isEmptyToNull = false, JsonSerializerSettings jsonSettings = null)
        {
            string response = string.Empty;

            if (!EqualityComparer<T>.Default.Equals(data, default(T)))
                response = JsonConvert.SerializeObject(data, jsonSettings);

            return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
        }

        public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
        {
            var response = default(T);

            if (!string.IsNullOrEmpty(data))
                response = jsonSettings == null
                    ? JsonConvert.DeserializeObject<T>(data)
                    : JsonConvert.DeserializeObject<T>(data, jsonSettings);

            return response;
        }
    }
}


And to use:

File.WriteAllText(sfd.FileName, JsonConverter.FromClass(listBox1.Items.OfType<Person>()));



UPDATE #2: You will always have blank files because of this line:

var myForm = new FormVer();


Instead of creating a new form with empty data, you need to point to the active form with the data. Something like:

var myForm = Application.OpenForms[nameof(FormVer)];


这篇关于如何在文本文件中保存列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆