Reine Viray
Reine Viray

Reputation: 75

Make textbox default value equals to 0

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

Answers (3)

Cleriston
Cleriston

Reputation: 770

Things you should consider:

  • Instead of setting the text attribute, sent its VALUE.
  • Verify your value before converting it. You are comparing it from null, but it is a DBNull. Check this information in addition to your Null validation.

Good luck!

Upvotes: 0

Khuram Nawaz
Khuram Nawaz

Reputation: 115

Instead of using null, use DBNull.

if(value != DBNull)
{
// update textbox
}

Upvotes: 0

Hari Prasad
Hari Prasad

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

Related Questions