ASP.Net Error: Specified cast is not valid

Last Reply 3 months ago By pandeyism

Posted 3 months ago

Hi,

i am facing this exception on this line.

int d = (int)dr["TTW"];

when my ExecuteReader is null

here is my c# code

protected void DDLContno_SelectedIndexChanged(object sender, EventArgs e)
{
    String strQuery = "select ConWeight from Containerno where  CID=@CID";
    SqlConnection con = new SqlConnection();
    SqlCommand cmde = new SqlCommand();
    cmde.Parameters.AddWithValue("@CID", DDLContno.SelectedValue);
    cmde.CommandType = CommandType.Text;
    cmde.CommandText = strQuery;
    cmde.Connection = con;
    try
    {
        con.Open();
        SqlDataReader sdr = cmde.ExecuteReader();
        while (sdr.Read())
        {

            txtTweght.Text = sdr[0].ToString();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {

    }
    if
        (txtctweight.Text != "")
    {
        String S2 = "Select Sum(IWeight) as TTW from ConIssuance where CID='" + DDLContno.SelectedValue + "'";
        SqlCommand cmd = new SqlCommand(S2, con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        if (dr.Read())
        {

            int? d = (int?)dr["TTW"];
            TBSTDID.Visible = true;
            txtctweight.Text = Convert.ToString(d);
        }

        {
            int a = Convert.ToInt32(txtTweght.Text);
            int b = Convert.ToInt32(txtctweight.Text);
            int d = a - b;
            TextBox1.Text = Convert.ToString(d);
            con.Close();
            con.Dispose();
        }

    }
}

please guide

You are viewing reply posted by: pandeyism 3 months ago.
Posted 3 months ago
akhter says:
"Select Sum(IWeight) as TTW from ConIssuance where CID='" + DDLContno.SelectedValue + "'";

 If your query return null value so integer throw error for that you need to make nullable int refer link and make nullable integer.