C# Windows Form中如何清空FlowLayoutPanel?时间表应用开发问题
解决方案
要解决新数据追加到FlowLayoutPanel的问题,只需在生成新控件前清空现有内容即可,同时可以优化数据库资源的管理方式提升代码可靠性。
核心修改:清空现有控件
在执行数据读取逻辑前,调用flowLayoutPanel1.Controls.Clear()就能直接清空面板内的所有现有控件,避免新旧数据叠加。
修改后的完整代码
private void GetData() { string selected = comboBox1.Text; // 清空FlowLayoutPanel的现有内容 flowLayoutPanel1.Controls.Clear(); // 使用using语句自动管理数据库资源,避免泄漏 using (SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-GCV9BH6\SQLEXPRESS01;Initial Catalog=Timetabler;Integrated Security=True")) { con.Open(); using (SqlCommand command = new SqlCommand("select CourseID, CourseName, LecturerName,ProgrammeName from courses where ProgrammeName= @ProgrammeName", con)) { command.Parameters.AddWithValue("@ProgrammeName", selected); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { unit = new Label(); unit.Text = dr["CourseName"].ToString(); unit.Width = 120; unit.Height = 95; unit.BackColor = Color.WhiteSmoke; unit.TextAlign = ContentAlignment.MiddleCenter; tutor = new Label(); tutor.Text = dr["LecturerName"].ToString(); tutor.Width = 80; tutor.BackColor = Color.FromArgb(247, 167, 82); tutor.TextAlign = ContentAlignment.MiddleCenter; unit.Controls.Add(tutor); flowLayoutPanel1.Controls.Add(unit); unit.Cursor = Cursors.Hand; } } } } }
额外优化说明
- 资源自动释放:用
using语句包裹SqlConnection、SqlCommand和SqlDataReader,无需手动调用Close(),系统会自动释放相关资源,避免因疏忽导致的数据库连接泄漏。 - 彻底释放控件资源(可选):如果控件占用内存较多,可通过遍历方式逐个移除并销毁控件,比
Clear()更彻底:
while (flowLayoutPanel1.Controls.Count > 0) { var control = flowLayoutPanel1.Controls[0]; flowLayoutPanel1.Controls.Remove(control); control.Dispose(); }
内容的提问来源于stack exchange,提问作者Kadre Dobson
相关产品推荐
相关产品推荐

