尝试相应地从一个dataGridView转移到另一个

时间:2014-01-18 00:21:09

标签: c# .net datagridview

我的datagridView1包含7列,第一列包含日期。 我正在尝试将january数据从dataGridView1传输到dataGridView2 我确实尝试使用循环,逻辑上认为它可以工作,但它会给我nullExceptions

这是我的代码:

 for (int i = 0; i < f1.dataGrivView1.Rows.Count; i++)
        {
                if (f1.dataGrivView1.Rows[i].Cells[0].Value.ToString().Split('/')[1].StartsWith("01"))//if january..
                {
                    dataGrivView1.Rows.Add();//datagridview in current form
                    dataGrivView1.Rows[i].Cells[0].Value = f1.dataGrivView1.Rows[i].Cells[0].Value.ToString();
                    dataGrivView1.Rows[i].Cells[1].Value = f1.dataGrivView1.Rows[i].Cells[1].Value.ToString();
                   }}

经过一些谷歌搜索,我看到你不能只是这样复制数据,你需要克隆它,所以我试过。

            foreach (DataGridViewRow dgvr in f1.dataGridView1.Rows)
            {
                DataGridViewRow r = dgvr.Clone() as DataGridViewRow;
                foreach (DataGridViewCell cell in dgvr.Cells)
                {
                    if (cell.Value.ToString().Contains("/01/"));
                    r.Cells[cell.ColumnIndex].Value = cell.Value;
                }

                dataGridView1.Rows.Add(r);
            }

但是......同样的事情。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这确实将第一列值从DataGridView复制到另一个。

for(int i=0; i<f1.dataGridView1.Rows.Count; i++)
    dataGridView1.Rows[i].Cells[0].Value = f1.dataGridView1.Rows[i].Cells[0].Value;

抛出的任何异常可能是由于新的dataGridView1在迭代中没有相应索引处的现有行。