Datatable with class constructor methods for registering

Asked

Viewed 57 times

0

I’m trying to make a DataTable that saves data (I’m not using database) relating to a customer’s name and email and displays in a DataGridView (display on the grid is not the problem, this I know how to do) the data that was typed in the textbox. I started messing with DataTable yesterday and read that it is better for my application than a List<T>, I’ve used to add and delete to a registration program.

Below I put the code of the class Data and its attributes and methods, but I would like to receive help to understand how to get the method of my class (which in the case is the Name that is typed in the text box txt_nome and the Email which is received in txt_email) and put him inside the DataTable. Below I put the parts of the code I already have and are relevant:

public partial class Form1 : Form
{

    DataSet ds = new DataSet();
    DataTable dt = new DataTable("Cadastro");

..........

private void bt_salvar_Click_1(object sender, EventArgs e)
{       
DataRow dr = dt.NewRow();
        dr["Nome"] = txt_nome.Text;

        dt.Rows.Add(dr);
        ds.Tables.Add(dt);

        dataGridView1.DataSource = dt;
}

...............

public class Dados
{

    private string _nome;
    private string _email;

    //construtor para iniciar os dados privados - recebe parametros
    public Dados(string nome, string email)
    {
        this._nome = nome;

        this._email = email;
    }


    public string Nome
    {
        get
        {
            return _nome;
        }
        set
        {
            _nome = value;
        }
    }

    public string Email
    {
        get
        {
            return _email;
        }
        set
        {
            _email = value;
        }
    }
}

If I’m talking nonsense I’m sorry, I’m beginner and I’m trying to learn everything well in the best way (I’m looking for various views on each subject of c#).

1 answer

1


I don’t know if it’s exactly what you wanted, but I put down an example using your class Dados

private void bt_salvar_Click_1(object sender, EventArgs e)
{       
        //No segundo parâmetro, que está vazio, você pode colocar o email
        //digitado em algum textbox, por exemplo.
        Dados dados = new Dados(txt_nome.Text, "");
        DataRow dr = dt.NewRow();

        //Aqui, em vez de pegarmos direto da textbox, pegamos do atributos
        //do objeto que declaramos logo acima
        dr["Nome"] = dados.Nome;

        //Você também poderia, por exemplo, colocar o email em alguma coluna        
        //dr["Email"] = dados.Email;

        dt.Rows.Add(dr);
        ds.Tables.Add(dt);

        dataGridView1.DataSource = dt;
}

If you want to read the data later, you can go through the DataGrid, reading your lines and filling in the objects.

  • Exactly that, thank you very much!!

Browser other questions tagged

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