GridView 使用 DropDownList 出现绑定空值的异常处理

本文介绍ASP.NET中使用GridView控件结合DropDownList实现数据编辑的方法。一种方式是在编辑模板中直接设置DropDownList的SelectedValue属性,另一种则是在_RowUpdating事件中获取DropDownList的值更新到数据源。文中还涉及了绑定事件及获取控件实例的具体步骤。

<asp:TemplateField HeaderText="父节点">
                    <EditItemTemplate>
                         <asp:DropDownList ID="DropDownList1"  runat="server"
                            DataSourceID="SqlDataSource_ZipNode" DataTextField="DistrictDesc"
                            DataValueField="DistrictId"  SelectedValue='<%# Bind("ParentId") %>'
                             AppendDataBoundItems="True" ondatabinding="DropDownList1_DataBinding"
                             ondatabound="DropDownList1_DataBound"
                             onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                            
                             <asp:ListItem Enabled="false"></asp:ListItem>
                            
                        </asp:DropDownList>
                        <asp:SqlDataSource ID="SqlDataSource_ZipNode" runat="server"
                            ConnectionString="<%$ ConnectionStrings:connStr %>" 
                            SelectCommand="prd_SelectDistrictNodes" SelectCommandType="StoredProcedure">
                        </asp:SqlDataSource>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("ParentId") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

 

要点已经标出

 

 

//上面这种方法有局限性,还有一种通用的方法

 <EditItemTemplate> 模版里的DropDownList 不用SelectedValue绑定

在GridView事件 _RowUpdating

 DropDownList objtemp_ZipId=GV_SheBeiDelete.Rows[e.RowIndex].FindControl("DropDownList3") as DropDownList;
        DropDownList objtemp_DvsTypeId = GV_SheBeiDelete.Rows[e.RowIndex].FindControl("DropDownList4") as DropDownList;
        e.NewValues["ZipId"] = objtemp_ZipId.Text;
        e.NewValues["DvsTypeId"] = objtemp_DvsTypeId.Text;

 

当然对于编辑模版里的 DropDownList 要写事件  DropDownList4_DataBound
 DropDownList obj = sender as DropDownList;
        try
        {
            obj.Text = DvsTypeId_GV_SheBeiDelete; ; //变量,其取值在GridView的RowEditing事件里

        }
        catch
        {

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值