如何从datatable到datagridview获取某些列?

时间:2011-08-17 18:35:53

标签: c#

我有一个数据表,我想从中提取某些信息(只有某些行,只有某些列)。我正在尝试使用下面的代码,但是当我运行它时,我得到的索引超出范围错误,我不确定我正在做的是从数据表中获取特定数据的最佳方法到datagridview。有什么想法吗?

        currentRow = 0;
        int dataGridRow = 0;
        foreach (DataRow row in resultsDT.Rows)
        {
            string value = resultsDT.Rows[currentRow]["HighLow"].ToString();
            if (value.Equals("High") | value.Equals("Low"))
            {
                dataGridView2.Rows[dataGridRow].Cells["colHighLow"].Value = resultsDT.Rows[currentRow]["HighLow"];
                dataGridView2.Rows[dataGridRow].Cells["colDifference"].Value = resultsDT.Rows[currentRow]["Difference"];
                dataGridView2.Rows[dataGridRow].Cells["colMbrSep"].Value = resultsDT.Rows[currentRow]["MBRSEP"];
                dataGridView2.Rows[dataGridRow].Cells["colLocation"].Value = resultsDT.Rows[currentRow]["LOCATION"];
                dataGridView2.Rows[dataGridRow].Cells["colDistrict"].Value = resultsDT.Rows[currentRow]["DIST"];
                dataGridView2.Rows[dataGridRow].Cells["colAddress"].Value = resultsDT.Rows[currentRow]["ADDR1"];
                dataGridView2.Rows[dataGridRow].Cells["colMeter"].Value = resultsDT.Rows[currentRow]["METER"];
                dataGridView2.Rows[dataGridRow].Cells["colKWh"].Value = resultsDT.Rows[currentRow]["KWH"];
                dataGridRow++;
            }
            currentRow++;
        }

1 个答案:

答案 0 :(得分:2)

我只能猜到你需要的是什么

   currentRow = 0;
        int dataGridRow = 0;
        foreach (DataRow row in resultsDT.Rows)
        {
            string value = resultsDT.Rows[currentRow]["HighLow"].ToString();
            if (value.Equals("High") | value.Equals("Low"))
            {
                //THIS LINE
                dataGridView2.Rows.Add();

                dataGridView2.Rows[dataGridRow].Cells["colHighLow"].Value = resultsDT.Rows[currentRow]["HighLow"];
                dataGridView2.Rows[dataGridRow].Cells["colDifference"].Value = resultsDT.Rows[currentRow]["Difference"];
                dataGridView2.Rows[dataGridRow].Cells["colMbrSep"].Value = resultsDT.Rows[currentRow]["MBRSEP"];
                dataGridView2.Rows[dataGridRow].Cells["colLocation"].Value = resultsDT.Rows[currentRow]["LOCATION"];
                dataGridView2.Rows[dataGridRow].Cells["colDistrict"].Value = resultsDT.Rows[currentRow]["DIST"];
                dataGridView2.Rows[dataGridRow].Cells["colAddress"].Value = resultsDT.Rows[currentRow]["ADDR1"];
                dataGridView2.Rows[dataGridRow].Cells["colMeter"].Value = resultsDT.Rows[currentRow]["METER"];
                dataGridView2.Rows[dataGridRow].Cells["colKWh"].Value = resultsDT.Rows[currentRow]["KWH"];
                dataGridRow++;
            }
            currentRow++;
        }