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

如何将存储过程生成的BindingSource绑定到GridView并解决只读报错

解决方案

报错根本原因

DevExpress GridView 是依附于 GridControl 的视图组件,没有可写入的DataSource属性,它的数据源默认继承自所属GridControl绑定的数据源,不需要也不能手动给GridView的DataSource赋值,直接删除报错的那行代码即可。

完整修正步骤

1. 前置问题修正(避免后续其他报错)

存储过程语法修正

你当前的存储过程存在语法缺陷,调整后示例:

-- 替换成你自己的存储过程名,比如GetStudentTuition
create procedure GetStudentTuition
    @StudentID VARCHAR(50) -- 补充参数类型,和你表的StudentID字段类型一致
as 
begin
    -- 补充需要查询的字段,避免select * 拉取冗余字段
    select t.StudentID, t.Years, t.Semester, t.FeeAmount, d.PaymentDate, d.PaymentAmount
    from [TuitionFee] t
    left outer join [Detailed_TuitionFee] d 
        on t.StudentID = d.StudentID 
        and t.Semester = d.Semester
        and t.Years = d.Years -- 建议加年份匹配,避免同学生同学期不同年份的数据混乱
    where t.StudentID = @StudentID
    -- 删掉原来的Detailed_TuitionFee的where条件,否则会把左连接变成内连接,丢失未缴费的记录
end

C#调用存储过程逻辑修正

避免直接拼接SQL字符串导致注入风险,调整调用逻辑:

BindingSource bdsTuitionInfo = new BindingSource();
string studentID = "实际要查询的学生ID"; // 先给studentID赋值
GridControl gCtrlTuition = new GridControl();
// 先将GridView和GridControl关联
GridView gViewTuition = new GridView(gCtrlTuition);
gCtrlTuition.MainView = gViewTuition;

// 参数化调用存储过程,更安全
string sqlCmd = "exec GetStudentTuition @StudentID = @SID";
// 你的ExecSqlDataTable方法如果支持传参,就传入对应参数,不支持的话至少拼接时加空格:
// string sqlCmd = $"exec GetStudentTuition '{studentID}'";

DataTable dt = Program.ExecSqlDataTable(sqlCmd);
bdsTuitionInfo.DataSource = dt;
// 仅需给GridControl绑定数据源即可,GridView会自动同步
gCtrlTuition.DataSource = bdsTuitionInfo;

2. GridView 可选配置调整

如果需要自定义显示效果,可按需添加以下配置:

// 自动根据数据源字段生成列
gViewTuition.OptionsBehavior.AutoPopulateColumns = true;
gViewTuition.PopulateColumns();

// 自定义列显示名、是否可见、显示格式
gViewTuition.Columns["StudentID"].Caption = "学生ID";
gViewTuition.Columns["FeeAmount"].Caption = "应缴金额";
gViewTuition.Columns["PaymentAmount"].Caption = "实缴金额";
gViewTuition.Columns["PaymentDate"].Caption = "缴费日期";
// 隐藏不需要的字段
// gViewTuition.Columns["Years"].Visible = false;

// 常用交互配置
gViewTuition.OptionsBehavior.Editable = false; // 表格只读不可编辑
gViewTuition.OptionsView.ShowGroupPanel = false; // 隐藏顶部分组面板
gViewTuition.OptionsView.ColumnAutoWidth = true; // 列宽自动适配控件宽度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:45:05