You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数据库及列表填充CheckedListBox,求排查代码问题

代码中存在的问题及修正建议
  • 资源泄漏风险:数据库连接、命令、数据阅读器都未通过using语句管理。这些类型实现了IDisposable接口,不用using的话,一旦代码抛出异常,Close()方法可能无法执行,导致数据库连接无法及时释放,耗尽连接池。
    修正示例:

    using (SqlCommand getlocationnames = new SqlCommand("allLocationNames", conn))
    {
        getlocationnames.CommandType = CommandType.StoredProcedure; 
        conn.Open();
        using (SqlDataReader dr = getlocationnames.ExecuteReader())
        {
            List<locations> results = new List<locations>();
            while (dr.Read())
            {
                locations newItem = new locations();
                newItem.loc_name = dr.IsDBNull(0) ? string.Empty : dr.GetString(0);
                results.Add(newItem);
            }
        }
        conn.Close();
    }
    
  • CheckedListBox显示异常:直接将locations对象添加到Items集合中,控件默认会调用对象的ToString()方法,显示的会是类的全名(比如YourNamespace.locations)而非loc_name的值。
    两种修正方式:

    1. 重写locations类的ToString()方法:
      public class locations
      {
          public string loc_name { get; set; }
          public override string ToString()
          {
              return loc_name;
          }
      }
      
    2. 添加时直接传入loc_name值:
      foreach (var result in results)
      {
          checkedListBox1.Items.Add(result.loc_name);
      }
      
  • 数据读取不安全:dr.GetString(0)假设第一列一定是字符串且不为null,如果数据库中该列允许为NULL,会抛出InvalidCastException,应该先判断是否为DBNull再读取,如上面代码示例中的dr.IsDBNull(0) ? string.Empty : dr.GetString(0)。

  • 缺失异常处理:数据库操作容易出现网络故障、权限不足、存储过程不存在等问题,没有异常捕获的话会直接导致程序崩溃,建议添加try-catch块处理异常,比如:

    try
    {
        // 数据库操作代码
    }
    catch (SqlException ex)
    {
        // 处理SQL相关异常,比如提示用户
    }
    catch (Exception ex)
    {
        // 处理其他异常
    }
    

内容的提问来源于stack exchange,提问作者bvsta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:06:23