Editing Row by a textbox and receiving in the datatable

Asked

Viewed 504 times

0

I have a class that has two methods that receive what is typed in textBox, all this stored in one dataTable (without database). When I click on a line (Row) of dataGridView I show the values saved in dataTable back in the textBox and so I can change the value of textBox, but not save in dataTable because I don’t know how to add this change.

If anyone can help me I’d really 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();
}>

  • See if I can help you... I don’t know if your problem is to set the value to the Datatable Datarow or if it is to take the Rowindex value.

2 answers

0

Hello, need to have line input (rowIndex) and take the option of Readonly and set as example below:

(rowIndex you take the grid as selected row 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]";

0

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

Your doubt would be at the time of updating the data, since you need to know the index of the line you are changing, which can be stored in a variable at the beginning of the Form thus:

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

and double-click this variable to the index of the 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();
}

At the moment of clicking the button to save the changes pass the line’s input with the values again:

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

ready so you are already updating the data on DataTable.


Complete 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, Alter and Save check on the buttons each operation performed.

Browser other questions tagged

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