计算一个DataTable中有多少项
本文关键字:多少 DataTable 一个 计算 | 更新日期: 2023-09-27 18:10:55
我有这个表单,其中文本框保存客户端的教育信息。我把这些文本框放在数组中,这样我就可以单独调用它们,并从我的数据表中向它们输入信息。我使用for循环和计数器来实现这一点,因为它是数据表中的行数。我想知道是否有一种方法可以计算其中的项目数量,以便我可以将计数器更改为更大的值并避免所有这些其他计数器:
TextBox[] arrayE = {
txtSchoolN1, txtDegree1, txtStartD1, txtEndD1,
txtSchoolN2, txtDegree2, txtStartD2, txtEndD2,
txtSchoolN3, txtDegree3, txtStartD3, txtEndD3,
txtSchoolN4, txtDegree4, txtStartD4, txtEndD4,
txtSchoolN5, txtDegree5, txtStartD5, txtEndD5,
txtSchoolN6, txtDegree6, txtStartD6, txtEndD6,
};
int[] counter = { 0, 1, 2, 3 };
for (int x = 0; x < dataTable.Rows.Count; x++)
{
arrayE[counter[0]].Text = dataTable.Rows[x][0].ToString().Trim();
arrayE[counter[1]].Text = dataTable.Rows[x][1].ToString().Trim();
arrayE[counter[2]].Text = dataTable.Rows[x][2].ToString().Trim();
arrayE[counter[3]].Text = dataTable.Rows[x][3].ToString().Trim();
counter[0] += 4;
counter[1] += 4;
counter[2] += 4;
counter[3] += 4;
}
简而言之,我想缩短我的代码
使用第二个嵌套循环:
int[] counter = { 0, 1, 2, 3 };
for (int x = 0; x < dataTable.Rows.Count; x++) {
for (int i = 0; i < counter.Length; i++) {
arrayE[counter[i]].Text = dataTable.Rows[x][i].ToString().Trim();
counter[i] += 4;
}
}
或者,不带计数器数组:
for (int x = 0; x < dataTable.Rows.Count; x++) {
for (int y = 0; y < 4; i++) {
arrayE[4 * x + y].Text = dataTable.Rows[x][y].ToString().Trim();
}
}
有一个办法。
var arrayE = new[]
{
new[] {txtSchoolN1, txtDegree1, txtStartD1, txtEndD1},
new[] {txtSchoolN2, txtDegree2, txtStartD2, txtEndD2},
new[] {txtSchoolN3, txtDegree3, txtStartD3, txtEndD3},
new[] {txtSchoolN4, txtDegree4, txtStartD4, txtEndD4},
new[] {txtSchoolN5, txtDegree5, txtStartD5, txtEndD5},
new[] {txtSchoolN6, txtDegree6, txtStartD6, txtEndD6}
};
for (var x = 0; x < dataTable.Rows.Count; x++)
{
arrayE[x][0].Text = dataTable.Rows[x][0].ToString().Trim();
arrayE[x][1].Text = dataTable.Rows[x][1].ToString().Trim();
arrayE[x][2].Text = dataTable.Rows[x][2].ToString().Trim();
arrayE[x][3].Text = dataTable.Rows[x][3].ToString().Trim();
}
够短吗?
int countOne = 0;
for (int x = 0; x < dataTable.Rows.Count; x++)
{
for (int y = 0; y <= 3; y++)
{
arrayE[countOne + y].Text = dataTable.Rows[x][y].ToString().Trim();
}
countOne += 4;
}