ASPxGridView中ASPxRadioButtonList致ObjectDataSource传空值的问题
你遇到的问题是:在ASPxGridView的自定义编辑表单里使用ASPxRadioButtonList选择性别,但通过ObjectDataSource执行插入操作时,Gender参数总是传入null。这是因为默认情况下,ObjectDataSource无法自动识别并获取EditForm中自定义控件的值,需要我们手动关联或者使用DevExpress内置的列编辑器来解决。
下面提供两种可行的解决方案:
方案一:利用ObjectDataSource的Inserting事件手动赋值
这种方法适合你已经使用自定义EditForm的场景,通过后台事件将RadioButtonList的选中值传递给Insert参数:
- 首先确保你的ASPxRadioButtonList有明确的ID(你的代码里是
Gender1,可以保留),然后给ObjectDataSource添加OnInserting事件绑定:
<asp:ObjectDataSource ID="ObjectDSEmployee" runat="server" InsertMethod="InsertEmployee" TypeName="solution.file1.DataAccess.InspectionDataAccess" OnInserting="ObjectDSEmployee_Inserting"> <InsertParameters> <asp:Parameter Name="Gender" Type="String"/> </InsertParameters> </asp:ObjectDataSource>
- 在后台代码(.aspx.cs文件)中实现
ObjectDSEmployee_Inserting方法,获取RadioButtonList的选中值并赋值给插入参数:
protected void ObjectDSEmployee_Inserting(object sender, ObjectDataSourceMethodEventArgs e) { // 从GridView的编辑表单中找到RadioButtonList控件 ASPxRadioButtonList genderRadioList = gvEmp.FindEditFormTemplateControl("Gender1") as ASPxRadioButtonList; if (genderRadioList != null && genderRadioList.Value != null) { // 将选中值传递给InsertEmployee方法的Gender参数 e.InputParameters["Gender"] = genderRadioList.Value.ToString(); } }
方案二:使用DevExpress内置的GridViewDataRadioButtonColumn(推荐)
这种方法更符合DevExpress的最佳实践,不需要手动处理事件,GridView会自动管理编辑控件和数据源的绑定:
修改你的GridView列定义,把原来的GridViewDataTextColumn替换为GridViewDataRadioButtonColumn,内置的列编辑器会自动在编辑模式下渲染单选按钮列表,并且自动将选中值传递给ObjectDataSource:
<dx:ASPxGridView ID="gvEmp" ClientInstanceName="gvEmp" runat="server" Width="100%" KeyFieldName="Emp_id" AutoGenerateColumns="false" DataSourceID="ObjectDSEmployee"> <Columns> <dx:GridViewDataRadioButtonColumn Caption="Gender" FieldName="Gender" ShowInCustomizationForm="true"> <PropertiesRadioButtonList ValueType="System.String"> <Items> <dx:ListEditItem Text="Male" Value="Male" /> <dx:ListEditItem Text="Female" Value="Female" /> </Items> </PropertiesRadioButtonList> </dx:GridViewDataRadioButtonColumn> <!-- 其他列定义 --> </Columns> <SettingsEditing Mode="EditFormAndDisplayRow" /> </dx:ASPxGridView>
这样设置后,当你进入编辑/插入模式时,GridView会自动显示单选按钮列表,选中的值会直接映射到Gender字段,ObjectDataSource在执行Insert时就能正确获取到参数值,不需要额外的事件处理。
为什么原来的代码会传null?
你之前的代码中,EditForm里的ASPxRadioButtonList只是通过Eval("Gender")显示了当前值,但它并没有和GridView的编辑数据源建立双向绑定关系,ObjectDataSource无法自动识别这个自定义控件的选中值,所以默认会传入null。通过上面两种方法,我们要么手动把控件值传递给参数,要么使用内置列让GridView自动处理绑定,就能解决这个问题。
内容的提问来源于stack exchange,提问作者Kumar

