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

C# Winform采用MVP架构绑定数据库数据到DataGridView报错求解

你遇到的报错根本原因是ProductPresenter中productview.gvData.Add(row)这行代码的参数类型错误:DataGridViewRowCollection.Add()方法不支持直接传入DataRow类型的对象,所以触发了类型不匹配异常。


快速修复方案(保持现有代码结构)

修改ProductPresenter的GetProduct方法,将DataRow的值转为数组后再添加:

public bool GetProduct()
{
    DataTable productDt = product.GetProductData();
    productview.gvData.Clear();
    foreach(DataRow row in productDt.Rows)
    {
        // 传入DataRow的值数组,而非DataRow本身
        productview.gvData.Add(row.ItemArray);
    }
    return true;
}

注意提前将dtgvProduct的AutoGenerateColumns属性设为true,或者手动设置列的DataPropertyName和数据库字段名对应,避免数据不显示。


推荐优化方案(符合MVP低耦合设计规范)

你当前的IProduct接口直接暴露了DataGridViewRowCollection这种WinForm控件专属类型,导致View和Presenter耦合度过高,不符合MVP的设计原则,建议按以下方式调整:

  1. 修改IProduct接口,替换控件专属属性为通用数据源属性
public interface IProduct
{
    int ProductID { get; set; }
    string ProductName { get; set; }
    float Price { get; set; }
    string Unit { get; set; }
    string Description { get; set; }
    string Original { get; set; }
    string ProductType { get; set; }
    string message { get; set; }
    // 新增通用数据源属性,删除原gvData属性
    object ProductDataSource { get; set; }
}
  1. 修改ProductForm的接口实现
// 替换原gvData属性的实现
public object ProductDataSource 
{
    get { return dtgvProduct.DataSource; }
    set { dtgvProduct.DataSource = value; }
}
  1. 修改ProductPresenter的GetProduct方法,直接绑定数据源
public bool GetProduct()
{
    productview.ProductDataSource = product.GetProductData();
    return true;
}

其他需要修复的潜在问题

  1. 数据库连接未释放,修改ConnectDB的GetData方法,用using自动释放连接,避免内存泄漏:
public DataTable GetData(string sqlquery)
{
    using(SqlConnection connect = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=ComesticDB;Integrated Security=True"))
    {
        SqlDataAdapter sqldata = new SqlDataAdapter(sqlquery, connect);
        DataTable dataTable = new DataTable();
        sqldata.Fill(dataTable);
        return dataTable;
    }
}
  1. 类型不匹配问题:Product模型类中ProductType是int类型,但IProduct接口中ProductType是string类型,建议统一类型,避免后续转换报错。

内容的提问来源于stack exchange,提问作者Chen Triều

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:08