[英]C# Looping to populate more than one DataGridView
我知道這是一個愚蠢的問題,我可能聽起來有點困惑(因為我確實是)。我正在為工作編寫軟件,但是我對C#還是陌生的。 我有一個帶有TabControl的窗體。 在每個TabPage中,我都有一個DataGridView。
我需要為每個DataGridView執行此代碼
while (reader.Read())
{
DataTable dtSchema = reader.GetSchemaTable();
DataTable dt = new DataTable();
// You can also use an ArrayList instead of List<>
List<DataColumn> listCols = new List<DataColumn>();
if (dtSchema != null)
{
foreach (DataRow drow in dtSchema.Rows)
{
string columnName = System.Convert.ToString(drow["ColumnName"]);
DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));
column.Unique = (bool)drow["IsUnique"];
column.AllowDBNull = (bool)drow["AllowDBNull"];
column.AutoIncrement = (bool)drow["IsAutoIncrement"];
listCols.Add(column);
dt.Columns.Add(column);
}
}
// Read rows from DataReader and populate the DataTable
while (reader.Read())
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < listCols.Count; i++)
{
dataRow[((DataColumn)listCols[i])] = reader[i];
}
dt.Rows.Add(dataRow);
}
dataGridView1 = dt;
}
reader.NextResult();
我不想復制並粘貼每個datagridview的代碼,因為在此代碼部分中唯一應更改的詞是DGV的名稱,但我不知道如何自動更改datagridview的名稱。 如果將datagridview的名稱與字符串進行比較,也許可以嵌套一些,這是一個解決方案,但是我想datagridview.tostring()不會給我控件名稱的字符串,而是內容。 如果這樣的問題已經存在,我很抱歉,我找不到它。
您可以使用foreach
DGV:
foreach (DataGridView dgv in new[] { dataGridView1, otherDGV })
{
// code to happen to both DGVs goes here.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.