Reputation: 23
I know this is kind of a stupid question and i may sound a bit confused ('cause i really am).I'm programming a software for work but i'm new to c#. I have a Form with a TabControl. In each TabPage i have a DataGridView.
i need to execute this code for each 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();
I don't want to copy and paste the code for each datagridview because the only words that should change in this code portion is the name of the DGV but i don't know how to automatically change the datagridview name. Maybe some nested if to compare the name of the datagridview with a string could be a solution but i suppose that datagridview.tostring() doesn't give me the string of the control's name but the content. i'm sorry if a question like this already existed, i wasn't able to find it.
Upvotes: 1
Views: 366
Reputation: 19486
You can use foreach
to loop over the DGVs:
foreach (DataGridView dgv in new[] { dataGridView1, otherDGV })
{
// code to happen to both DGVs goes here.
}
Upvotes: 2