sourabhgk
sourabhgk

Reputation: 99

Grid copy values from one column to another

I have data in grid in the following format.

Code                Option1    Option2
----------------------------------------
Finance Charges     100        0
Insurance Charges   200        0
Other Charges       300        0
Bank Charges        400        0

I want to copy values from Option1 column to Option2 column using code

Code                Option1    Option2
----------------------------------------
Finance Charges     100        100
Insurance Charges   200        200
Other Charges       300        300
Bank Charges        400        400

Awaiting for your reply.

Thanks.

Upvotes: 0

Views: 955

Answers (3)

Ravi
Ravi

Reputation: 1172

assign the value of column Option 1 to Option 2 for each Row

for (int i = 0; i < dataGrid.Rows.Count; i++)
{
        dataGrid.Rows[i].Cells["Option2"].Value=dataGrid.Rows[i].Cells["Option1"].Value;
} 

Upvotes: 0

Ram Kumaran
Ram Kumaran

Reputation: 661

Since you haven't explained if your case is for Winforms or WPF, I'm assuming its Winforms. The below linq based single liner will help your case.

dataGridView.Rows.Cast<DataGridViewRow>().ToList().ForEach(x => x.Cells[2].Value = x.Cells[1].Value);

ForEach linq method which we use to iterate over all items is available only on type that implements IList<T>, on the other hand Rows is a DataGridViewRowCollection that implements IEnumerable only, hence we convert that into List<DataGridViewRow> before we can apply transformation.

Upvotes: 0

Tom&#225;š Filip
Tom&#225;š Filip

Reputation: 817

for (int rows = 0; rows < dataGrid.Rows.Count; rows++).ToString()
{
        dataGrid.Rows[rows].Cells[2].Value=dataGrid.Rows[rows].Cells[1].Value;
} 

Upvotes: 1

Related Questions