How to save and upload data from a . txt to a gridview?

Asked

Viewed 4,198 times

7

It’s been two days since I’ve been looking for help for my problem, but everything I think doesn’t fit. I’m doing a simple program, as if it were an agenda, where I put all the records of my store. I don’t need anything complicated.

I made a DataGridView, but not connected to a database, I want it to store its information in a file .txt in the same folder. I need it to save the fields entered in the GridView, as name, leased product, value paid, date and etc.

But I need everything to be well separated, and when I open the program it pulls all this information saved in the file back. I have made some attempts, I have not found any method to save the data written on GridView.

In short:

-I need to know how to read a cell’s text GridView and thus save this text to my archive .txt.

-I need to know how to pull the information from the file .txt , but with all the separate information, that is, each cell with your due information.

Here’s what I’ve done so far:


namespace Cadastro_e_Informações_de_Clientes
{
    public partial class Form1 : Form
    {
        public Form1()
        {                                   
            InitializeComponent();
        }

        private void bSalvar_Click(object sender, EventArgs e)
        {   
            //Fiz um botão para pegar os dados escritos nas text boxes (tNome, tLocacao, tProduto etc...) e passar-los para o GridView
            //Como eu ainda não sei um método de salvar o texto diretamente da célula do GridView, eu fiz isso para salvar no momento do cadastro.

            if (this.tNome.Text == String.Empty || this.tProduto.Text == String.Empty || this.tLocacao.Text == String.Empty || this.tVencimento.Text == String.Empty || this.tPago.Text == String.Empty || this.tDivida.Text == String.Empty || this.tAdicional.Text == String.Empty)
            {
                string mensagem = "Um dos campos de texto não foi preenchido.\nDeseja continuar?";
                string titulo = "Aviso!";
                MessageBoxButtons Botoes = MessageBoxButtons.OKCancel;

                DialogResult resultado = MessageBox.Show(mensagem, titulo, Botoes, MessageBoxIcon.Warning);

                if (resultado == DialogResult.OK)
                {
                    this.Planilha.Rows.Add(tNome.Text, tProduto.Text, tLocacao.Text, tVencimento.Text, tPago.Text, tDivida.Text, tAdicional.Text);
                    FileStream Dados = new FileStream("C:/Users/Win/Desktop/Empresa/Dados.txt", FileMode.Append);

                    BinaryWriter bw = new BinaryWriter(Dados);
                    //grava uma string no arquivo
                    bw.Write(tNome.Text + "\t" + tProduto.Text + "\t" + tLocacao.Text + "\t" + tVencimento.Text + "\t" + tPago.Text + "\t" + tDivida.Text + "\t" + tAdicional.Text + "\n");
                    bw.Close();
                }
                else
                {
                    string mCancelada = "Operação cancelada.";
                    string tCancelada = "Cancelado!";
                    MessageBoxButtons cBotoes = MessageBoxButtons.OK;
                    MessageBox.Show(mCancelada, tCancelada, cBotoes, MessageBoxIcon.Information);
                }
            }
            else
            {
                this.Planilha.Rows.Add(tNome.Text, tProduto.Text, tLocacao.Text, tVencimento.Text, tPago.Text, tDivida.Text, tAdicional.Text);

                FileStream Dados = new FileStream("C:/Users/Win/Desktop/Empresa/Dados.@hR", FileMode.Append);

                BinaryWriter bw = new BinaryWriter(Dados);
                //grava uma string no arquivo
                bw.Write(tNome.Text + tProduto.Text + tLocacao.Text + tVencimento.Text + tPago.Text + tDivida.Text + tAdicional.Text);
                bw.Close();
            }
            tAdicional.Clear();
            tNome.Clear();
            tProduto.Clear();
            tVencimento.Clear();
            tPago.Clear();
            tDivida.Clear();
            tLocacao.Clear();
        }

        private void timerEditavel_Tick(object sender, EventArgs e)
        {
            // Esta é a opção de editar o GridView, porém, aqui está um de meus principais problemas.
            //Preciso ler o texto das células para que quando eu edite uma delas, eu possa ler as celulas e salvar no arquivo.txt.
            if (checkEditar.Checked)
            {
                cCliente.ReadOnly = false;
                cProduto.ReadOnly = false;
                cPago.ReadOnly = false;
                cAdic.ReadOnly = false;
                cVencimento.ReadOnly = false;
                cLocação.ReadOnly = false;
                cDivida.ReadOnly = false;
                timerEditavel.Stop();  
            }
            else
            {
                timerEditavel.Start();
                cCliente.ReadOnly = true;
                cProduto.ReadOnly = true;
                cPago.ReadOnly = true;
                cAdic.ReadOnly = true;
                cCliente.ReadOnly = true;
                cLocação.ReadOnly = true;
                cDivida.ReadOnly = true;
                //Isso abaixo foram as tentativas que fiz para ler as células. Más nenhuma delas lê realmente
                //o texto escrito nas células.
                tNome.Text = cCliente.ToString();
                tProduto.Text = cProduto.Index.ToString();
                tPago.Text = cPago.ToolTipText.ToString();
                tAdicional.Text = cPago.Index.ToString();
                tVencimento.Text = cVencimento.Index.ToString();
                tLocacao.Text = cLocação.Index.ToString();
                tDivida.Text = cDivida.Index.ToString();                
            }
        }

        private void checkTimer_Tick(object sender, EventArgs e)
        {
            if (!checkEditar.Checked)
            {
                timerEditavel.Start();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Adiciona uma linha vazia ao GridView
            this.Planilha.Rows.Add("", "", "", "", "", "", "");
        }

        private void lTimer_Tick(object sender, EventArgs e)
        {
            lInfo.Text = "Preencha os campos mostrados acima com as informações do Cliente e clique no botão para salvar na planilha.\nOs dados serão mostrados na planilha da aba 'Cadastros' e serão salvos no arquivo 'dados.bin' na pasta do programa.\nNo caso de algum erro ou problema durante a utilização deste programa, por favor, clique na aba 'Ajuda' e digite o erro acontecido.\nAtualizações com mais optimizações e aperfeissoamentos do código poderão vir.\nObrigado!";
        }
    }
}

  • Why don’t you use Microsoft Access? This application already has option to create Table and Forms that you can mount.

  • You can create a new wheel and spend a few more days trying or using a wheel that already exists, I think much better the 2nd option

  • I agree with the previous comments, now if there is any impediment to using a database, ever thought about using files xml? I’ve had to create applications for PDA s and to persist the data used xml. With the commands .ReadXml and .WriteXml it is simple to load and save the DataGridView.

4 answers

5

I agree with @Luisalexandrerodrigues that the best would be to save in a database and data, and Sqlite EF6 would be perfect for this kind of thing.

but I will consider that there is a need to save the data in a text file that is easily read and understood by Humans.

In this case I believe that the best format ceja the CSV (although XML is a great candidate).

To make life easier, we will use a Nugget in the following examples: Linqtocsv

Now let’s go to code.

Model

public class Item
{
    [CsvColumn(FieldIndex = 0, Name = "Nome", CanBeNull = false)]
    public String Nome { get; set; }

    [CsvColumn(FieldIndex = 1, Name = "Produto", CanBeNull = false)]
    public String Produto { get; set; }

    [CsvColumn(FieldIndex = 2, Name = "Locacao", CanBeNull = false)]
    public String Locacao { get; set; }

    [CsvColumn(FieldIndex = 3, Name = "Vencimento", CanBeNull = false)]
    public DateTime Vencimento { get; set; }

    [CsvColumn(FieldIndex = 4, Name = "Pago", CanBeNull = false, NumberStyle = NumberStyles.Currency)]
    public Decimal Pago { get; set; }

    [CsvColumn(FieldIndex = 5, Name = "Divida", CanBeNull = false, NumberStyle = NumberStyles.Currency)]
    public Decimal Divida { get; set; }

    [CsvColumn(FieldIndex = 6, Name = "Adicional", CanBeNull = false, NumberStyle = NumberStyles.Currency)]
    public Decimal Adicional { get; set; }
}

Form - Load

public partial class FrmPlanilha : Form
{
    private BindingSource source;
    private CsvFileDescription options;

    public FrmPlanilha()
    {
        InitializeComponent();

        this.source = new BindingSource();
        this.options = new CsvFileDescription
        {
            SeparatorChar = ';',
            FirstLineHasColumnNames = true,
            FileCultureName = "pt-BR"
        };

        var context = new CsvContext();
        var itens = context.Read<Item>(@"C:\temp\itens.csv", options).ToList();

        this.source.DataSource = itens;
        this.dgvItens.AutoGenerateColumns = true;
        this.dgvItens.DataSource = this.source;
    }
    ...
}

Add New Item

In the following example filling the Item object with random data, however you should do it with real data.

private void btAdicionar_Click(object sender, EventArgs e)
{
    var item = new Item
    {
        Nome = Guid.NewGuid().ToString(),
        Produto = Guid.NewGuid().ToString(),
        Locacao = Guid.NewGuid().ToString(),
        Vencimento = DateTime.Now,
        Divida = 0,
        Pago = 0,
        Adicional = 0
    };

    var itens = this.source.List as List<Item>;
    itens.Add(item);

    this.dgvItens.DataSource = null;
    this.dgvItens.DataSource = this.source;
}

Saving

private void btSalvar_Click(object sender, EventArgs e)
{
    var context = new CsvContext();
    context.Write(this.source.List as List<Item>, @"C:\temp\itens.csv", this.options);
}
  • 1

    CSV is the path to this type of data in my view, because in addition to being able to manipulate by your application other programs of tables can manipulate the same.

3

To complement Luis Alexandre’s response:

I prefer to go through a dataGridView as follows:

for(i=0;i < (SeuGrid.Rows.Count - 1);i++)
{
     DataGridViewTextBoxCell tnome = (DataGridViewTextBoxCell)SeuGrid.Rows[i].Cell[1];
     DataGridViewTextBoxCell tproduto = (DataGridViewTextBoxCell)SeuGrid.Rows[i].Cell[2];
     DataGridViewTextBoxCell tlocalizacao = (DataGridViewTextBoxCell)SeuGrid.Rows[i].Cell[3];
     
     string nome = tnome.Value;
     string produto = tproduto.Value;
     string localizacao = tlocalizacao.Value;
}

although it seems more complicated, the use of Datagridviewtextboxcell may allow some advantages depending on the application, such as changing the cell value (tnome.Value = "novo valor"), if necessary, etc....

to save in txt I found a good link to use as guide: http://imasters.com.br/artigo/12197/dotnet/leitura-e-escrita-em-arquivos-com-c/

On each line you concatenate the information you want into a line.

You can give the space that is needed for you, you can concatenate with a string with spaces: string spc = " ";

I don’t know what your goal is, but I prefer XML like Luisalexandre also suggested.

2

To read the contents of Gridview you could try the following:

foreach(GridViewRow row in SeuGridView.Rows)
{
    for(int i = 0; i < SeuGridView.Columns.Count, i++)
    {
        String header = SeuGridView.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

To persist the data, I think the best option is to use some database such as MS Access, Mysql, SQL Server, Oracle, etc.

In any case, if the need allows saving the data in XML, try using the Dataset class. It has methods for reading and writing XML files. See:

http://msdn.microsoft.com/pt-br/library/system.dataset.writexml(v=vs.90). aspx

-3

                  {
                    int row = 0;
                    dgwPedidoVenda.Rows.Add();
                    row = dgwPedidoVenda.Rows.Count - 1; //-2
                    dgwPedidoVenda["ID", row].Value = txtId.Text;
                    dgwPedidoVenda["Nome", row].Value = txtNome.Text;
                    dgwPedidoVenda["Produto", row].Value = txtProduto.Text;
                    dgwPedidoVenda["Vencimento", row].Value = txtVencimento.Text;
                 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.