我如何从datatable到datagridview获得某些列
本文关键字:datagridview datatable | 更新日期: 2023-09-27 18:05:59
我有一个数据表,我想从中提取某些信息(仅某些行和某些列)。我试图使用下面的代码,但我得到一个索引超出范围的错误,当我运行它,我不确定我所做的是最好的方式来获取某些数据从一个数据表到一个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++;
}
我只能猜你需要的是什么
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++;
}