I saved an object of type DataTable into SQL 2005 database in a field of type varbinary. I want to retrieve it back but I wasn't able to type cast it. This is how i saved it.
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(dt);
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Tables(TableName, TableData, QuestionID) VALUES (@TableName, @TableData, @QuestionID)", con))
{
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = "a new table";
cmd.Parameters.Add("@TableData", SqlDbType.VarBinary,Int32.MaxValue).Value = memStream.GetBuffer();
cmd.Parameters.Add("@QuestionID", SqlDbType.VarChar).Value = "2";
cmd.ExecuteNonQuery();
}
The 'dt' is the DataTable object instance.