在表单上动态添加usercontrol时,我获得了正确的输出
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName from Employee", myDatabaseConnection))
using (SqlDataAdapter da = new SqlDataAdapter(SqlCommand))
{
SqlDataReader DR1 = SqlCommand.ExecuteReader();
int y = 0;
while (DR1.Read())
{
y++;
for (int i = 0; i < y; i++)
{
UserControl2 userconrol = new UserControl2();
userconrol.Location = new Point(50, 30 * i);
userconrol.Tag = i;
userconrol.LastName = (string)DR1["LastName"];
this.Controls.Add(userconrol);
}
}
}
}
但是当我使用flowlayoutpanel动态添加控件时,这就是发生的事情:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName from Employee", myDatabaseConnection))
using (SqlDataAdapter da = new SqlDataAdapter(SqlCommand))
{
SqlDataReader DR1 = SqlCommand.ExecuteReader();
int y = 0;
while (DR1.Read())
{
y++;
for (int i = 0; i < y; i++)
{
UserControl2 userconrol = new UserControl2();
userconrol.Tag = i;
userconrol.LastName = (string)DR1["LastName"];
flowLayoutPanel1.Controls.Add(userconrol);
}
}
}
}
有什么问题?我使用相同的循环为什么当我使用flowlayoutpanel动态添加控件时它不会显示相同的输出?
答案 0 :(得分:1)
将FlowLayoutPanel的FlowDirection()更改为TopDown。
编辑:
另外,摆脱for循环......应该做什么?
也许是这样的?
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName from Student", myDatabaseConnection))
using (SqlDataAdapter da = new SqlDataAdapter(SqlCommand))
{
int i = 0;
SqlDataReader DR1 = SqlCommand.ExecuteReader();
while (DR1.Read())
{
i++;
UserControl2 userconrol = new UserControl2();
userconrol.Tag = i;
userconrol.LastName = (string)DR1["LastName"];
flowLayoutPanel1.Controls.Add(userconrol);
}
}
}
答案 1 :(得分:0)
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand SqlCommand = new SqlCommand("Select LastName from Employee", myDatabaseConnection))
using (SqlDataAdapter da = new SqlDataAdapter(SqlCommand))
{
List<string> list1 = new List<string>();
SqlDataReader DR1 = SqlCommand.ExecuteReader();
while (DR1.Read())
{
list1.Add((string)DR1["LastName"]);
}
int i = 0;
foreach (string LastName in list1)
{
i++;
UserControl2 userconrol = new UserControl2();
userconrol.Tag = i;
userconrol.LastName = LastName;
flowLayoutPanel1.Controls.Add(userconrol);
}
}
}