WinForms从数据库读多行数据但Panel仅显示一条的问题求助
问题分析与解决
你的代码存在两个核心问题,导致仅显示一条数据:
- 反复将同一个
panel1添加到flowLayoutPanel1:WinForms控件不能被重复添加到容器中,第二次添加操作会被系统忽略。 - 所有
labelName都添加到同一个panel1:后续创建的标签会和之前的标签位置重叠(默认位置一致),最终只能看到最后一条数据的标签。
修正方案
每次循环创建一个新的Panel来承载当前行的控件,再将这个新Panel添加到FlowLayoutPanel中。同时用using语句自动管理数据库连接资源,避免资源泄漏。
修正后的代码:
private void Form1_Load(object sender, EventArgs e) { // 使用using自动释放连接资源 using (var conn = new SqlConnection(@"data source=Acerv5; Database=Customers; integrated security= true")) { conn.Open(); SqlCommand command = new SqlCommand("Select * from Panel", conn); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // 为每一行数据创建独立的Panel Panel rowPanel = new Panel(); rowPanel.Size = new Size(flowLayoutPanel1.Width - 20, 30); rowPanel.BorderStyle = BorderStyle.FixedSingle; // 可选:添加边框区分各行 // 创建ID标签 Label labelID = new Label(); labelID.Text = reader[0].ToString(); labelID.Location = new Point(10, 5); labelID.AutoSize = true; // 创建名称标签 Label labelName = new Label(); labelName.Text = reader[1].ToString(); labelName.Location = new Point(80, 5); // 错开位置避免重叠 labelName.AutoSize = true; // 将标签添加到当前行的Panel rowPanel.Controls.Add(labelID); rowPanel.Controls.Add(labelName); // 将行Panel添加到FlowLayoutPanel flowLayoutPanel1.Controls.Add(rowPanel); } } } }
额外优化建议
- 如果希望ID和名称自动排列,可在每个行Panel中嵌套一个
FlowLayoutPanel,无需手动设置Location,布局更灵活。 - 将
flowLayoutPanel1的AutoScroll属性设为true,数据过多时可滚动查看。
内容的提问来源于stack exchange,提问作者khin yadanarphyoewaianar
相关产品推荐
相关产品推荐

