Konstantin Hadzhiev
Konstantin Hadzhiev

Reputation: 195

Data Grid View alter all the values of a specific column

I am really new to Data grid view, so my question could seem pretty basic to most of you. I have a database table with passwords. These passwords are encrypted. I have a C# app with a datagridview which shows me this table, but I see the encrypted passwords, and i would like to see them decrypted.

This code populates my datagrid with the database table named Companies(each company has a password):

private void populateCompaniesDataGrid()
        {
            String sql = "SELECT * from companies";
            MySqlCommand command = new MySqlCommand(sql, dh.Connection);

            try
            {
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                adapter.SelectCommand = command;
                DataTable dbdataset = new DataTable();
                adapter.Fill(dbdataset);
                BindingSource bSource = new BindingSource();

                bSource.DataSource = dbdataset;
                dataGridView1.DataSource = bSource;
                adapter.Update(dbdataset);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                dh.Connection.Close();
            }
        }

I have a class DataEncryptor, which has 2 methods - Encrypt and Decrypt.

private DataEncryptor encryptor = new DataEncryptor();
public string Encrypt(string text)
    {
       //does some stuff to encrypt
        return Encrypt;
    }

    public string Decypt(string text)
    {
        //does some stuff to decrypt
        return Decrypt;
    } 

Upvotes: 0

Views: 750

Answers (2)

nevra
nevra

Reputation: 428

You can add this and call your Decyrpt method.

void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
            {
                if (e.ColumnIndex == 1 && e.RowIndex != this.dataGridView1.NewRowIndex)
                {
                    e.Value = Decrypt(e.Value.ToString());
                }
            }

Upvotes: 1

iamwillie
iamwillie

Reputation: 56

Maybe try RowsAdded event? Then within the loop add your code to read the password, call you decrypt method and write the string back to the row.

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    for (int i = e.RowIndex; i < e.RowCount + e.RowIndex; i++)
    {
        //not tested: 
        string password = dataGridView1.Rows[e.RowIndex].Cells["encryptedPassword"].Value.ToString()
        string decryptedPassword = DataEncryptor.Decrypt(password);

        dataGridView1.Rows[e.RowIndex].Cells["encryptedPassword"].Value = decryptedPassword;
        Console.WriteLine("Row " + i.ToString() + " added");
    }
}

gridview rowdatabound event in winforms?

Upvotes: 0

Related Questions