locked
Unable to cast object of type System.String to type System.Byte. RRS feed

  • Question

  • User-367318540 posted

    i am facing this exception that 

    Unable to cast object of type 'System.String' to type 'System.Byte[]'.

    <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
            <%--<asp:Image ID="img" runat="server" ImageUrl='<%# Eval("Data").ToString() %>' Height="100px" Width="100px" />--%>
            <asp:Image  ID="Data" runat="server" Width="100px" Height="80px"  ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Data")) %>' />
        </ItemTemplate>
    </asp:TemplateField>

    Monday, September 23, 2019 11:48 AM

Answers

  • User665608656 posted

    Hi akhterr,

    As mgebhard said, the issue is on this code:

    if (Session["Buyitems"] == null)
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;

    From this judgment, it is obvious that Session["Buyitems"] is null at this time.

    After you convert it into datatable, dt is also null, so a series of code for dt operation will be wrong.

    If you want to operate on dt, the premise is that Session["Buyitems"] is not null.

    I suggest you need to use breakpoints to debug your code step by step.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 24, 2019 2:56 AM

All replies

  • User475983607 posted

    The error message seems very clear.  The code is trying to convert a string to a byte[].  I assume "Data" is a string and not a byte[] as expected?

    <asp:Image  ID="Data" runat="server" Width="100px" Height="80px"  
    ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Data")) %>' />

    Can you explain how your code works and provide the data type for "Data"?

    Monday, September 23, 2019 1:46 PM
  • User-367318540 posted

    i am passing data from datalist to another page gridview . On datalist i am selecting multiple item to pass another page using session.

    here is my c# code for passing data on another page ...

     protected void btn_Add_Click(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                DataRow dr;
                dt.Columns.Add("sno");
                dt.Columns.Add("ProductName");
                dt.Columns.Add("Price");
                dt.Columns.Add("Name");
                dt.Columns.Add("CustomerID");
                dt.Columns.Add("Data");
    
                foreach (DataListItem item in dlemp.Items)
                {
                    Label customerID = item.FindControl("CustomerID") as Label;
                    Label price = item.FindControl("Price") as Label;
                    CheckBox selectedpizza = item.FindControl("CheckBox1") as CheckBox;
                    if (selectedpizza.Checked)
                    {
                        if (Session["Buyitems"] == null)
                        {
    
                            dr = dt.NewRow();
                            con.Open();
                            String myquery = "select * from Productitem where Product_id=" + customerID.Text;
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myquery;
                            cmd.Connection = con;
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = cmd;
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            dr["sno"] = sr + 1;
                            dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
                            dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
                            dr["CustomerID"] = ds.Tables[0].Rows[0]["Product_id"].ToString();
                            dr["Name"] = ds.Tables[0].Rows[0]["Name"].ToString();
                            byte[] bytes = (byte[])ds.Tables[0].Rows[0]["Data"];
                            //First way
                          //  string base64String1 = Convert.ToBase64String(bytes, 0, bytes.Length);
                            // Second Way
                            string base64String2 = "data:image/jpg;base64," + Convert.ToBase64String((byte[])ds.Tables[0].Rows[0]["Data"]);
                            //dr["productimage"] = ds.Tables[0].Rows[0]["Data"].ToString();
                            con.Close();
                            dt.Rows.Add(dr);
                            Session["buyitems"] = dt;
                        }
                        else
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;
    
                            dr = dt.NewRow();
                            //   con.Open();
                            String myquery = "select * from Productitem where Product_id=" + customerID.Text + "";
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myquery;
                            cmd.Connection = con;
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = cmd;
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            dr["sno"] = sr + 1;
                            dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
                            dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
                            dr["CustomerID"] = ds.Tables[0].Rows[0]["Product_id"].ToString();
                            dr["Name"] = ds.Tables[0].Rows[0]["name"].ToString();
                            byte[] bytes = (byte[])dt.Rows[0]["Data"];
                            //First way
                            string base64String1 = Convert.ToBase64String(bytes, 0, bytes.Length);
                            // Second Way
                            string base64String2 = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dt.Rows[0]["Data"]);
                             
    
    
                            dt.Rows.Add(dr);
                            Session["buyitems"] = dt;
    
                        }
                    }
    
                }
                Response.Redirect("ShopingCart.aspx");
    
            }
    
            protected void dlemp_ItemCommand(object source, DataListCommandEventArgs e)
            {
    
                if (e.CommandName == "view")
                {
                    Response.Redirect("ViewDetails.aspx?Id=" + e.CommandArgument.ToString());
                }
    
            }
    
           
        }
    }

    second page c# code

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Jewelleryonlineshop
    {
        public partial class ShopingCart : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                DataTable dt;
                dt = (DataTable)Session["buyitems"];
                GridView1.DataSource = dt;
                GridView1.DataBind();
    
            }
    
            protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                int index = Convert.ToInt32(e.RowIndex);
                DataTable dt = (DataTable)Session["buyitems"];
                dt.Rows[index].Delete();
                Session["buyitems"] = dt;
                GridView1.DataSource = dt;
                GridView1.DataBind();
    
    
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                try
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        DataRowView dr = (DataRowView)e.Row.DataItem;
                        string imageUrl = "data:images/jpg;base64," + Convert.ToBase64String((byte[])dr["Data"]);
                        (e.Row.FindControl("Data") as System.Web.UI.WebControls.Image).ImageUrl = imageUrl;
                    }
                }
                catch
                (Exception ex)
                { }
            }
    
        }
    }

    Monday, September 23, 2019 2:14 PM
  • User475983607 posted

    You did not answer the question.   What is the data type of "Data"?  Is it a string?  VARCHAR()?

    Monday, September 23, 2019 2:35 PM
  • User-367318540 posted

    data type is varbinary(MAX)

    Monday, September 23, 2019 2:38 PM
  • User475983607 posted

    akhterr

    data type is varbinary(MAX)

    This post is a little confusing.  Your first code snippet is related to data binding a standard data control.   The second post shows code that stores data in Session then redirects to the ShoppingCart page.  I assume the markup in the first post comes from the ShoppingCart page and where the error is thrown.

    If that's correct,  then the btn_Add_Click event never populates Session with a the "Data" byte array. 

    Or is the error thrown in the page that has the btn_Add_Click handler?  Can you explain how the code is supposed to work?  Have you tried running the code through the debugger to make sure the the data exists and is expected?  Have you checked the database to verify the varbinary(max) column has values and the values are correct?

    Monday, September 23, 2019 3:08 PM
  • User-367318540 posted

    Yes you are right, my first page is productselection in which i used datalist ,and also using checkbox and second page is shopping cart,,

    are you saying that byte will not pass through session?

    Monday, September 23, 2019 3:11 PM
  • User475983607 posted

    akhterr

    are you saying that byte will not pass through session?

    No. 

    I do not see anywhere in the code where the byte array populates the rd["Data"] field.   As far as I can, tell the Data column is always empty.

    Secondly, the btn_Add_Click handler logic appears to have other issues.  Are you sure the customerID  input contains the Product_id?  Seems like a mistake.

    String myquery = "select * from Productitem where Product_id=" + customerID.Text;

    I recommend that you take a step back and run your code through the Visual Studio debugger to make sure the code you wrote matches your expectations.

    On a side note, using Session to store a shopping cart is not not the a good design IMO.  It's much cleaner and more robust to store a shopping in a database table.  Session can to be volatile and you loss the ability to report abandoned carts.

    Monday, September 23, 2019 3:42 PM
  • User-367318540 posted

    Hi mgebhard,

    i debug already data is coming and data is coming on second page,issue is that when i used below code on second page to display image using session,then image does not get display ,

                                    <asp:Image ID="Data" runat="server" ImageUrl='Product_Images/<%# Eval("Data") %>' />

    if i am using below code then then that error is coming...and below code is working fine in other pages using gridview just facing this issue using session

     <%--<asp:Image  ID="Data" runat="server" style="margin-top:4%;" Width="50%" Height="50%"   ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Data")) %>' />--%>
    

    Monday, September 23, 2019 3:47 PM
  • User475983607 posted

    i debug already data is coming and data is coming on second page,issue is that when i used below code on second page to display image using session,then image does not get display ,

    The code shared above does not persist the byte array or base64 string in Session.  Set the "Data" column as shown below which by the way the data type defaults to a string since you did not specify the DataTable column type.

    dt = (DataTable)Session["buyitems"];
    int sr;
    sr = dt.Rows.Count;
    
    dr = dt.NewRow();
    //   con.Open();
    String myquery = "select * from Productitem where Product_id=" + customerID.Text + "";
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = myquery;
    cmd.Connection = con;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    dr["sno"] = sr + 1;
    dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
    dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
    dr["CustomerID"] = ds.Tables[0].Rows[0]["Product_id"].ToString();
    dr["Name"] = ds.Tables[0].Rows[0]["name"].ToString();
    byte[] bytes = (byte[])dt.Rows[0]["Data"];
    //First way
    string base64String1 = Convert.ToBase64String(bytes, 0, bytes.Length);
    // Second Way
    string base64String2 = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dt.Rows[0]["Data"]);
     
    dr["Data"] = base64String2;
    
    dt.Rows.Add(dr);
    Session["buyitems"] = dt;

    You'll need to change the second page which I assume is the ShoppingCart page since the "data" column contains the embedded image.

    <asp:Image  ID="Data" runat="server" Width="100px" Height="80px"  ImageUrl='<%# Server.HtmlEncode(Eval("Data")) %>' />

    I  think you need to Server.HtmlEncode otherwise the framework will encode the special characters.

    If you already have this working elsewhere then you should compare the code.

    Monday, September 23, 2019 6:32 PM
  • User-367318540 posted

    this exception is being raised 

    'Object reference not set to an instance of an object.'
     
    dt was null.

    Monday, September 23, 2019 7:12 PM
  • User475983607 posted

    this exception is being raised 

    'Object reference not set to an instance of an object.'</div> <div> </div> <div>dt was null.

    Seems strange that adding the line below which has nothing to do with the dt variable would cause a null references

    dr["Data"] = base64String2;

    I recommend debugging.  If you need community debugging support, you want the community to debug your code, then post the latest code changes.

    Monday, September 23, 2019 7:34 PM
  • User-367318540 posted

    here is whole code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    
    namespace Jewelleryonlineshop
    {
        public partial class WebForm2 : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection("Data Source=ATLANTIC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Shoppingcart;MultipleActiveResultSets=True;");
            private int sr;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindDatalist();
    
                    int TotalRows = this.BindList(1);
    
                    this.Prepare_Pager(TotalRows);
                }
                if (ViewState["CurrentPage"] != null)
    
                {
    
                    this.CurrentPage = Convert.ToInt32(ViewState["CurrentPage"]);
    
                }
            }
            public void BindDatalist()
            {
                SqlDataAdapter adp = new SqlDataAdapter("Select * from Productitem", con);
                DataTable dt = new DataTable();
                adp.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    dlemp.DataSource = dt;
                    dlemp.DataBind();
                }
            }
            private int CurrentPage = 1;
    
            private int ItemsPerPage = 5;
            protected void Pager_Click(object sender, EventArgs e)
    
            {
    
                LinkButton lnkPager = (LinkButton)sender;
    
                int PageNo = 1;
    
                switch (lnkPager.CommandName)
    
                {
    
                    case "Previous":
    
                        PageNo = this.CurrentPage - 1;
    
                        break;
    
                    case "Next":
    
                        PageNo = this.CurrentPage + 1;
    
                        break;
    
                }
    
                int TotalRows = this.BindList(PageNo);
    
                int PageCount = this.CalculateTotalPages(TotalRows);
    
                ViewState["CurrentPage"] = PageNo;
    
                if (PageNo == 1)
    
                {
    
                    lnkPrev.Enabled = false;
    
                }
    
                else
    
                {
    
                    lnkPrev.Enabled = true;
    
                }
    
                if (PageNo == PageCount)
    
                {
    
                    lnkNext.Enabled = false;
    
                }
    
                else
    
                {
    
                    lnkNext.Enabled = true;
    
                }
    
            }
    
            private int BindList(int PageNo)
    
            {
    
                int TotalRows = 0;
    
                DataTable dt = new DataTable();
    
    
                SqlDataAdapter sda = new SqlDataAdapter();
    
                SqlCommand cmd = new SqlCommand("spx_Pager");
    
                cmd.CommandType = CommandType.StoredProcedure;
    
                cmd.Parameters.Add("@PageNo", SqlDbType.Int).Value = PageNo;
    
                cmd.Parameters.Add("@ItemsPerPage", SqlDbType.Int).Value = ItemsPerPage;
    
                cmd.Parameters.Add("@TotalRows", SqlDbType.Int).Direction = ParameterDirection.Output;
    
                cmd.Connection = con;
    
                try
    
                {
    
                    con.Open();
    
                    sda.SelectCommand = cmd;
    
                    sda.Fill(dt);
    
                    dlemp.DataSource = dt;
    
                    dlemp.DataBind();
    
                    TotalRows = Convert.ToInt32(cmd.Parameters["@TotalRows"].Value);
    
                }
    
                catch (Exception ex)
    
                {
    
                    Response.Write(ex.Message);
    
                }
    
                finally
    
                {
    
                    con.Close();
    
                    sda.Dispose();
    
                    con.Dispose();
    
                }
    
                return TotalRows;
    
            }
            private int CalculateTotalPages(int intTotalRows)
    
            {
    
                int intPageCount = 1;
    
                double dblPageCount = (double)(Convert.ToDecimal(intTotalRows) / Convert.ToDecimal(this.ItemsPerPage));
    
                intPageCount = Convert.ToInt32(Math.Ceiling(dblPageCount));
    
                return intPageCount;
    
            }
    
            private void Prepare_Pager(int TotalRows)
    
            {
    
                int intPageCount = this.CalculateTotalPages(TotalRows);
    
                if (intPageCount > 1 && this.CurrentPage < intPageCount)
    
                {
    
                    this.lnkNext.Enabled = true;
    
                }
    
                if (this.CurrentPage != 1)
    
                {
    
                    this.lnkPrev.Enabled = true;
    
                }
    
                else
    
                {
    
                    this.lnkPrev.Enabled = false;
    
                }
    
            }
            protected void btn_Add_Click(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                DataRow dr;
                dt.Columns.Add("sno");
                dt.Columns.Add("ProductName");
                dt.Columns.Add("Price");
                dt.Columns.Add("Name");
                dt.Columns.Add("CustomerID");
                dt.Columns.Add("Data");
    
                foreach (DataListItem item in dlemp.Items)
                {
                    Label customerID = item.FindControl("CustomerID") as Label;
                    Label price = item.FindControl("Price") as Label;
                    CheckBox selectedpizza = item.FindControl("CheckBox1") as CheckBox;
                    if (selectedpizza.Checked)
                    {
                        if (Session["Buyitems"] == null)
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;
    
                            dr = dt.NewRow();
                            //   con.Open();
                            String myquery = "select * from Productitem where Product_id=" + customerID.Text + "";
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myquery;
                            cmd.Connection = con;
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = cmd;
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            dr["sno"] = sr + 1;
                            dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
                            dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
                            dr["CustomerID"] = ds.Tables[0].Rows[0]["Product_id"].ToString();
                            dr["Name"] = ds.Tables[0].Rows[0]["name"].ToString();
                            byte[] bytes = (byte[])dt.Rows[0]["Data"];
                            //First way
                            string base64String1 = Convert.ToBase64String(bytes, 0, bytes.Length);
                            // Second Way
                            string base64String2 = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dt.Rows[0]["Data"]);
    
                            dr["Data"] = base64String2;
    
                            dt.Rows.Add(dr);
                            Session["buyitems"] = dt;
                        }
                        else
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;
    
                            dr = dt.NewRow();
                            //   con.Open();
                            String myquery = "select * from Productitem where Product_id=" + customerID.Text + "";
                            SqlCommand cmd = new SqlCommand();
                            cmd.CommandText = myquery;
                            cmd.Connection = con;
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = cmd;
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            dr["sno"] = sr + 1;
                            dr["ProductName"] = ds.Tables[0].Rows[0]["ProductName"].ToString();
                            dr["Price"] = ds.Tables[0].Rows[0]["Price"].ToString();
                            dr["CustomerID"] = ds.Tables[0].Rows[0]["Product_id"].ToString();
                            dr["Name"] = ds.Tables[0].Rows[0]["name"].ToString();
                            dr["Data"] = ds.Tables[0].Rows[0]["Data"].ToString();
                        
                            dt.Rows.Add(dr);
                            Session["buyitems"] = dt;
    
                        }
                    }
    
                }
                Response.Redirect("ShopingCart.aspx");
    
            }
    
            protected void dlemp_ItemCommand(object source, DataListCommandEventArgs e)
            {
    
                if (e.CommandName == "view")
                {
                    Response.Redirect("ViewDetails.aspx?Id=" + e.CommandArgument.ToString());
                }
    
            }
    
           
        }
    }

    on this line i am facing issue

      sr = dt.Rows.Count;
    Monday, September 23, 2019 7:46 PM
  • User475983607 posted

    This does not look good.

                        if (Session["Buyitems"] == null)
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;

    You're testing if Session["Buyitems"] is null and it Session["Buyitems"] is null you're setting null to dt.  

    I recommend slowing down and implementing a thorough review of your code before sharing the code on the forum.  IMHO, this is a pretty simple bug to find if you were using the debugger.

    Monday, September 23, 2019 7:57 PM
  • User665608656 posted

    Hi akhterr,

    As mgebhard said, the issue is on this code:

    if (Session["Buyitems"] == null)
                        {
    
                            dt = (DataTable)Session["buyitems"];
                            int sr;
                            sr = dt.Rows.Count;

    From this judgment, it is obvious that Session["Buyitems"] is null at this time.

    After you convert it into datatable, dt is also null, so a series of code for dt operation will be wrong.

    If you want to operate on dt, the premise is that Session["Buyitems"] is not null.

    I suggest you need to use breakpoints to debug your code step by step.

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 24, 2019 2:56 AM