Handling NULL from database to GridView

2019-08-26 21:13发布

问题:

I have a simple GridView that show some values directy from database. In database there's a column named MaxNoPlaces. That column represents maxlenght of TextBox with id ObjectValue. The problem is sometimes the value in the database is NULL and when I run the app binding fails and page cannot be loaded. How can I manage null in database and convert them to 0 in maxlenght to that textbox ?

Thanks in advance!

<asp:GridView ID="gvMyObjects" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" CssClass="GridView" AutoPostBack="False"  AutoGenerateColumns="False" >
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                    <ContentTemplate>
                        <button class="myBtn" id="Button1" type="button" data-toggle="modal" data-target="#myModal"  runat="server" ><span>Select</span></button>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="ID" >
            <ItemTemplate>
                <asp:Label ID="ObjectID" runat="server"   margin-Left="100px"  Text='<%# Bind("ObjekatID") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="ObjectName" runat="server" margin-Left="100px" Text='<%# Bind("ObjectName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Value">
            <ItemTemplate>
                <asp:TextBox ID="ObjectValue" runat="server" margin-Left="100px" MaxLength='<%# Bind("MaxNoPlaces") %>' Text='<%# Bind("ObjectValue") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Value">
            <ItemTemplate>
                <asp:Label ID="Object" runat="server" margin-Left="100px" Text='<%# Bind("Object") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>    
</asp:GridView>

回答1:

You can simply do it in sql query whenever you retrieving data just write

select ISNULL(MaxNoPlaces,0) as MaxNoPlaces FROM table_Name

so it will return 0 if database having NULL value.