Reputation: 75
I have set my textbox = 0
<p>Credit Balance: </p><asp:TextBox ID="txtCredit" runat="server" style="width:70px" Text = "0"></asp:TextBox>
and my code behind is this:
scn.Open();
SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM UserData WHERE Username=@Username", scn);
cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = Session["New"];
object value = cmd.ExecuteScalar();
if (value != null)
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
What i want to happen is if it has value, it will display it. if none, default value is equal to 0. But i am receiving an error
Object cannot be cast from DBNull to other types.
Upvotes: 0
Views: 2262
Reputation: 770
Things you should consider:
Good luck!
Upvotes: 0
Reputation: 115
Instead of using null, use DBNull.
if(value != DBNull)
{
// update textbox
}
Upvotes: 0
Reputation: 16956
I suspect, value is coming as DBNull
, you could guard against DBNull
using Convert.IsDBNull
method.
if (!Convert.IsDBNull(value))
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
Upvotes: 1