Question

I'm a little stumped as to how to fix an error here. I have a gridview with a series of numbers (samples of the way they appear in the database are below) that I want to add commas to. I'm attempting to get this done in the ASP code with a literal (code below). The table associated with the stuff below lets call foo and the column name is called 'count'. Without the TemplateField and the literal (noted below) the gridview works fine. However, when I add the TemplateField below, and I get an 'Object cannot be cast from DBNull to other types.' from the browser. All I'm trying to do is to get the gridview output to show commas in the ASP code and not the database.

What I've tried:

First I thought there might be some odd characters, trailing spaces or things like that so I ran the following command:

select * from foo where count not like '%[^0-9]%'

Only it returned every single entry in the table. I manually checked some of the results and there aren't any trailing spaces or odd characters in the columns I want to add commas to.

I'm pretty stumped as what to try next as I've been able to get this to work on my test server but not in production.

Column Sample

Count

2345342
4356546
3245234534
67465745675
43523452345
546234523452345
32452345
4352345234
4352345
345234

These are entered into the database as NVARCHAR(MAX) (nulls allowed) as we import data from a wide variety of sources.

Code

   <asp:TemplateField HeaderText="Count" SortExpression="count">
        <EditItemTemplate>
            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("count") %>'></asp:TextBox>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Literal ID="Literal1" runat="server" Text='<%# string.Format("{0:N0}", Convert.ToDecimal(Eval("count"))) %>'>
            </asp:Literal>
        </ItemTemplate>
        <HeaderStyle BackColor="#6699FF" />
    </asp:TemplateField>

Error

Object cannot be cast from DBNull to other types.

Était-ce utile?

La solution

I'm guessing somewhere you have a null and if you try to convert it to decimal in your template you would get that error. You'll need to put some code to disallow that.

string.Format("{0:N0}", Convert.ToDecimal(Eval("count")==DBNull.Value ? "0" : Eval("count")))

Autres conseils

Have you considered in your query wrapping the column that may contain nulls with an IsNull. Take the problem away at the database

select *,isnull([count],0) from foo where count not like '%[^0-9]%'

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top