Monday, July 21, 2008

When Databinding results in System.Byte[]

So - quite a few people seem to be having an issue with DataBinding to any sort of control (Dropdownlist, DataGrid, etc) resulting in the bound control printing out System.Byte[]. This may not be the one true answer, but it is definitely one of them.

I noticed a lot of people (like myself) were having trouble with MySql - specifically connector/net. The solution is simple, and probably affects other database storage engines just as well.

Basically - the just of it was this - here is my code to bind a DropDownList. Pretty readable stuff

----------------------------
string sql = "CALL Get_LFID_info('" + ddl_Log_Formats_1.SelectedValue + "');";
DataTable dts = ExecuteMySqlAdapter(sql);
relation1.DataSource = dts;
relation1.DataTextField = "extended_varname";
relation1.DataValueField = "variable_id";
relation1.DataBind();
----------------------------


The issue with this case was that my procedure calculated the result of "extended_varname" - which means that it was created by doing a SELECT CONCAT(name,".",id) sort of deal. Which meant there was no column type associated with it. The solution - pretty simple. Just cast the result. I did this - SELECT CAST(CONCAT(name,".",id) AS CHAR) AS extended_varname . While I believe that you might be able to so that simpler, it was the easy answer. If I figure out a better way to cast it, I will let you know - but the point is the general idea that the column needs to have a specific type associated with it before MySql Connector can correctly convert the rows to strings - any System.Byte[] result generally indicates a cast went wrong somewhere.

Hope that helps
-Hamy

References
mysql type conversion

3 comments:

Anonymous said...

Dude! I'm not an ASP.NET programmer, but I found myself having to figure out why I was getting System.Byte[] rather than the value that that was expected as a part of a calculated SQL statement. This post totally held the answer. Thank you! Thank you! Thank you!

So:
SELECT Sum(webcost * quantity) as PriceSum ...

became:
SELECT cast(Sum(webcost * quantity) as char) as PriceSum ...

I hate dealing with code that I didn't write (much less ASP.NET -- yuck!), but this saved me! Thanks! :)

Anonymous said...

Thanks, that was exactly what saved my day :-)

I had this problem only at the customers's machine, not on my development pc. The mySQL Libraries and databases are slightly different on both machines, so I guess it depends on the version if you experience this problem or not.

Another reason to code defensive ;-)

Best Regards & Thanks,
Ralf

JurajH said...

Thanks a lot. This solved my big issue.