Row editing by a textBox and receiving in the dataTable

0

I have a class that has two methods that get what is typed in textBox , all stored in dataTable (without database). When I click on a line ( Row ) of dataGridView I show the values saved in dataTable back in textBox so I can change the value of textBox , but do not save dataTable since it does not I know how to add this change.

If someone can help me, I would appreciate it.

<public class Dados
{
    private string _nome; 
    private string _email;

    public Dados(string nome, string email)
    {
        this._nome = nome;
        this._email = email;
    }

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

    public string Endereco
    {
        get{return _email;}

        set{_email = value;}
    }

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

    public string AlterarEndereco
    {
        get{return _email;}

        set{_email = value;}
    }


}>

// Part of Form1.cs

public Form1()
{
    InitializeComponent();

    dt.Columns.Add("Nome", Type.GetType("System.String"));
    dt.Columns.Add("Email", Type.GetType("System.String"));
    dataGridView1.DataSource = dt;
}

//salvar o que foi digitado
private void bt_salvar_Click_1(object sender, EventArgs e)
{

    Pessoa dados = new Pessoa(txt_nome.Text, txt_email.Text);
    DataRow dr = dt.NewRow();

    dr["Nome"] = dados.Nome;
    dr["Email"] = dados.Email;

    dt.Rows.Add(dr);
    dataGridView1.DataSource = dt;
}



//botão para editar
private void alterarToolStripMenu_Click_1(object sender, EventArgs e)
{

    //espera

    dataGridView1.Update();
    dataGridView1.Refresh();

}

//botão excluir row/cliente
private void excluirToolStripMenu_Click_1(object sender, EventArgs e)
{
    int indexDaLinhaSelecionada = dataGridView1.CurrentCell.RowIndex;

    dataGridView1.Rows.RemoveAt(indexDaLinhaSelecionada);

    dataGridView1.Update();
    dataGridView1.Refresh();
}>
    
asked by anonymous 09.03.2017 / 20:51

2 answers

0

Hello, need to have row index (rowIndex) and take the option of ReadOnly and set the example below:

(rowIndex takes the grid as the selected line is an integer)

     foreach(DataColumn col in dataTable1.Columns)
        {
            col.ReadOnly = false;
        }

  //  ... dataTable1.Rows[0] por exemplo
        int rowIndex = 0; 
        dataRow1[rowIndex]["Nome"] = "novoNome";
        dataRow1[rowIndex]["Email"] = "[email protected]";
    
04.05.2017 / 20:18
0

Good first thing, either you work with the class ( class ) in a typed list or you work with DataTable , in your code for example the class is useless, you can directly assign the values DataTable

Your doubt would be to update the data, since you need to know the index of the line that is changing, which can be stored in a variable at the beginning of the Form class like this:

public int Index { get; set; } = 0;

and double-click this variable for the index of Row that was clicked:

if (DataGridViewDados.CurrentRow.Index >= 0)
{
    Index = DataGridViewDados.CurrentRow.Index;
    TxtNome.Text = DataGridViewDados.Rows[Index].Cells[0].Value.ToString();
    TxtEmail.Text = DataGridViewDados.Rows[Index].Cells[1].Value.ToString();
}

When you click on the button to save the changes pass the index of the line with the values again:

DataRow row = DataTableDados.Rows[Index];
row["Nome"] = TxtNome.Text;
row["Email"] = TxtEmail.Text;

So you're already updating the data in DataTable .

Full Code:

using System;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {

        public DataTable DataTableDados { get; set; }
        public int Index { get; set; } = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Layout_Datatable();
            DataGridViewDados.DataSource = DataTableDados;
        }

        private void Layout_Datatable()
        {
            if (DataTableDados == null)
            {
                DataTableDados = new DataTable("Dados");
                DataTableDados.Columns.Add("Nome", Type.GetType("System.String"));
                DataTableDados.Columns.Add("Email", Type.GetType("System.String"));
                DataTableDados.Columns["Nome"].Unique = false;
                DataTableDados.Columns["Nome"].AllowDBNull = false;
                DataTableDados.Columns["Email"].Unique = false;
                DataTableDados.Columns["Email"].AllowDBNull = false;
            }
        }

        private void SetButtonTextBox(bool status = true)
        {
            TxtEmail.Clear();
            TxtEmail.Enabled = status;
            TxtNome.Clear();
            TxtNome.Enabled = status;
            BtuNovo.Visible = !status;
            BtuAlterar.Visible = !status;
            BtuSalvar.Visible = status;
            BtuCancelar.Visible = status;
            Tag = default(object);
            Index = default(int);
        }

        private void Update_DataGridView()
        {
            DataGridViewDados.Refresh();
            DataGridViewDados.Update();
        }

        private void BtuNovo_Click(object sender, EventArgs e)
        {            
            SetButtonTextBox();
            TxtNome.Focus();
            Tag = 1;
        }

        private void BtuAlterar_Click(object sender, EventArgs e)
        {
            if (DataTableDados.Rows.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show(
                    "Deseja alterar?",
                    "Alterar",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button1))
                {

                    SetButtonTextBox();
                    TxtNome.Focus();
                    Tag = 2;

                    if (DataGridViewDados.CurrentRow.Index >= 0)
                    {
                        Index = DataGridViewDados.CurrentRow.Index;
                        TxtNome.Text = DataGridViewDados.Rows[Index].Cells[0].Value.ToString();
                        TxtEmail.Text = DataGridViewDados.Rows[Index].Cells[1].Value.ToString();
                    }
                }
            }
            else
            {
                MessageBox.Show("Nenhum dado consta para alteração", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }           
        }

        private void BtuSalvar_Click(object sender, EventArgs e)
        {
            if (Tag != null)
            {
                if (Tag.Equals(1))
                {
                    DataRow row = DataTableDados.NewRow();
                    row["Nome"] = TxtNome.Text;
                    row["Email"] = TxtEmail.Text;
                    DataTableDados.Rows.Add(row);

                }
                else if (Tag.Equals(2))
                {
                    DataRow row = DataTableDados.Rows[Index];
                    row["Nome"] = TxtNome.Text;
                    row["Email"] = TxtEmail.Text;
                }
                SetButtonTextBox(false);
                Update_DataGridView();
            }
        }

        private void BtuCancelar_Click(object sender, EventArgs e)
        {
            SetButtonTextBox(false);
            Update_DataGridView();
        }

        private void DataGridViewDados_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                BtuAlterar.PerformClick();
            }
        }
    }
}

In this complete code are the operations of New , Change / em> check the buttons for each operation performed.

    
04.05.2017 / 21:33