网格将值从一列复制到另一列

时间:2018-10-22 07:10:36

标签: c#

我具有以下格式的网格数据。

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

我想使用代码将值从Option1列复制到Option2列

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

等待您的答复。

谢谢。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

由于您没有说明您的案例是Winforms还是WPF,因此我假设它是Winforms。以下基于linq的单衬板将帮助您解决问题。

dataGridView.Rows.Cast<DataGridViewRow>().ToList().ForEach(x => x.Cells[2].Value = x.Cells[1].Value);
用于迭代所有项目的

ForEach linq方法仅在实现IList 的类型上可用,另一方面,Rows是仅实现IEnumerable的DataGridViewRowCollection,因此在我们进行操作之前,将其转换为List 可以应用转换。

答案 2 :(得分:0)

为每行将选项1列的值分配给选项2

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