C# DataGridView无法检索SQL Server数据库全部记录问题
问题背景
基于Visual Studio开发的学生档案管理系统包含两个业务端:
- 在线报名应用:负责采集学生报名信息,数据写入SQL Server数据库存储
- 桌面管理应用:负责拉取数据库内的报名数据,用于后续业务流程处理
当前异常表现:桌面应用检索数据库数据时,DataGridView控件无法加载全部数据库记录。
涉及的数据展示代码如下:
private void DisplayOnlineApplications(List<StudentInformationOnlineModel> Applicants) { dataGridView1.Rows.Clear(); foreach (var applicant in Applicants) { string gender = applicant.Gender.Substring(0, 1); dataGridView1.Rows.Add(applicant.ApplicationID, applicant.StudentStatus, applicant.LRN, applicant.StudentName, gender, applicant.EmailAddress, applicant.MobileNo, applicant.EducationLevel, applicant.CourseStrand, applicant.YearLevel, applicant.ApplicationDate.ToString("MM-dd-yyyy hh:mm tt")); dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = applicant; } }
根因定位
代码中存在会直接中断加载流程的隐性异常点:
- 核心触发点是
applicant.Gender.Substring(0, 1)这行逻辑:只要任意一条报名记录的Gender字段为null或者空字符串,执行Substring时会直接抛出ArgumentOutOfRangeException,整个foreach循环会当场终止,异常条目之后的所有记录都不会被添加到控件中,最终表现为DataGridView只加载了异常点之前的部分数据。 - 次要排查方向:如果传入方法的
Applicants列表本身的条目数就和数据库符合查询条件的总记录数不一致,问题出在数据库查询层,需要检查SQL语句的过滤条件、分页参数是否错误拦截了数据。 - 视觉误差问题:逐行手动添加行时如果没有暂停控件重绘,大量数据加载时会出现UI渲染卡顿、滚动条长度计算错误,看起来像没加载全。
修复方案
- 首先补全空值判断,避免单条脏数据中断整个加载流程,替换原有的gender取值逻辑:
string gender = string.IsNullOrEmpty(applicant.Gender) ? string.Empty : applicant.Gender.Substring(0, 1); - 优化控件加载逻辑,增加重绘暂停逻辑解决渲染问题,改造后的完整方法如下:
private void DisplayOnlineApplications(List<StudentInformationOnlineModel> Applicants) { // 暂停控件重绘,提升大量数据加载时的渲染效率 dataGridView1.SuspendLayout(); dataGridView1.Rows.Clear(); foreach (var applicant in Applicants) { // 空值兼容处理,避免单条数据异常中断整个循环 string gender = string.IsNullOrEmpty(applicant.Gender) ? string.Empty : applicant.Gender.Substring(0, 1); int newRowIndex = dataGridView1.Rows.Add( applicant.ApplicationID, applicant.StudentStatus, applicant.LRN, applicant.StudentName, gender, applicant.EmailAddress, applicant.MobileNo, applicant.EducationLevel, applicant.CourseStrand, applicant.YearLevel, applicant.ApplicationDate.ToString("MM-dd-yyyy hh:mm tt") ); dataGridView1.Rows[newRowIndex].Tag = applicant; } // 恢复重绘,强制刷新控件显示 dataGridView1.ResumeLayout(); dataGridView1.Refresh(); } - 前置校验:调试时在
foreach循环前加断点,确认Applicants.Count和数据库查询出的总记录数一致,如果数量不匹配,优先排查数据查询层逻辑,无需在UI展示层浪费时间。
长期优化建议:手动逐行调用
Rows.Add加载数据的性能很差,数据量超过1000条时会明显卡顿。更稳妥的方式是直接将DataGridView.DataSource属性赋值为Applicants列表,通过列配置控制显示字段,自动绑定模式不会出现逐行加载的中断问题,加载效率能提升数倍。
内容的提问来源于stack exchange,提问作者Rommel Pabustan
相关产品推荐
相关产品推荐

