Obout Grid中静态DropDownList数据绑定后显示异常求助
解决Obout Grid中DropDownList更新后显示异常的问题
嘿,我看你遇到的问题很典型:Obout Grid里的DropDownList在更新数据库后,没法正确回显选中的值,总是默认显示第一项,但TextBox却能正常展示更新后的内容。这本质上是因为Grid每次绑定数据时会重新渲染模板控件,而你没有为DropDownList手动设置选中项——毕竟它的选项是静态定义的,Grid没办法自动匹配对应的值。
咱们一步步来修复这个问题:
1. 给Grid添加DataBound事件,手动设置DropDownList选中值
首先,在Grid的标签里加上OnDataBound事件,这样每次Grid绑定完数据,我们就能遍历每一行设置DropDownList的选中状态:
<cc1:Grid ID="Grid1" runat="server" AllowAddingRecords="true" CallbackMode="true" Serialize="true" EnableRecordHover="true" FolderStyle="Styles/style_13" AllowPaging="false" AllowPageSizeSelection="false" AutoGenerateColumns="false" Width= "100%" OnInsertCommand="InsertRecord" OnDeleteCommand="DeleteRecord" OnUpdateCommand="UpdateRecord" OnDataBound="Grid1_DataBound"> <!-- 新增这个事件 -->
然后在后台代码里实现这个事件方法:
protected void Grid1_DataBound(object sender, EventArgs e) { // 遍历Grid的每一条记录 foreach (GridRecord row in Grid1.Records) { // 找到当前行里的DropDownList控件 DropDownList ddBu = row.FindControl("ddBu") as DropDownList; if (ddBu != null) { // 获取当前行Bu字段的数据库值 string buDbValue = row["Bu"].ToString(); // 匹配DropDownList中对应的选项并设置选中 ListItem targetItem = ddBu.Items.FindByValue(buDbValue); if (targetItem != null) { ddBu.SelectedValue = buDbValue; } } } }
2. 确认Update/Insert方法中值的获取正确
从你描述的“能正确更新数据库”来看这部分应该没问题,但还是要确认一下在UpdateRecord中,你是正确获取DropDownList的选中值的,比如:
protected void UpdateRecord(object sender, GridRecordEventArgs e) { // 从Grid的更新记录中获取Bu字段的值(也就是用户选择的DropDownList值) string selectedBu = e.Record["Bu"].ToString(); // 执行数据库更新操作,把selectedBu写入对应字段 // ... 你的数据库更新代码 // 重新绑定Grid数据 populateInbound_detail(); }
为什么TextBox能正常显示?
因为TextBox在Grid列中通过DataField直接绑定了字段值,Grid会自动把数据库的值填充进去;而DropDownList是你手动定义的静态选项,Grid不知道该选中哪一项,必须我们手动匹配设置。
额外提醒
- 确保数据库中
Bu字段的值和DropDownList的Value完全一致(比如大小写、空格都要匹配),不然FindByValue会找不到对应的选项。 - 如果未来你的DropDownList选项需要动态从数据库获取,记得先在DataBound事件中绑定DropDownList的数据源,再设置选中值。
内容的提问来源于stack exchange,提问作者user1606540
相关产品推荐
相关产品推荐

