无法将类型为"System.String"的对象转换为类型为"System.Byte []"的对象.例外
问题描述:
我无法解决此异常,有人可以帮我解决这个问题.
此处提供代码:
I cant fix this exception, can someone help me with this.
Heres the code:
DataTable dt = new DataTable();
dt.Columns.Add("Marker", typeof(string));
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Page", typeof(string));
dt.Rows.Add("A1", "Desc1", "1");
dt.Rows.Add("A2", "Desc2", "2");
dt.Rows.Add("A3", "Desc3", "3");
dt.Rows.Add("A4", "Desc4", "4");
byte[] data = (byte[])dt.Rows[0][0];
richTextBox1.Rtf = System.Text.Encoding.Unicode.GetString(data);
预先感谢;
Thanks in advance;
答
最后2行
The last 2 lines
byte[] data = (byte[])dt.Rows[0][0];
richTextBox1.Rtf = System.Text.Encoding.Unicode.GetString(data);
应该是
Should be
richTextBox1.Rtf = dt.Rows[0][0].ToString();
无需尝试将字符串转换为字节数组再转换回字符串.
There is no need to try to convert the string to a byte array and back to a string.
尝试此
byte[] data = System.Text.Encoding.Unicode.GetBytes(dt.Rows[0][0].ToString ());
代替
instead of
byte[] data = (byte[])dt.Rows[0][0];