I have this case of data conversion in .NET dataset: I have a new database, I've queried a table into my dataset but I dont know exactly datatype of DataColumn of DataTable in the dataset and I want to insert some new data without knowing exactly the DataColumn.DataType at the design time. So, my idea is that I can use reflection to get the type of the DataColumn to insert the new data precisely. Would somebody please tell me whether can I do that and how to?
SomeDbDataAdapter da = new SomeDbDataAdapter("select * from table1", conn);
DataSet ds = new DataSet();
da.Fill(ds);
Int32 i = 1;
DataRow dr = ds.Tables[0].NewRow();
PropertyInfo colInfo = dr.GetType().GetProperty("COLUMN1");
Type t = ds.Tables[0].Columns["COLUMN1"].DataType;
colInfo.SetValue(dr, Convert.ChangeType(i, t), null);
ds.Tables[0].Rows.Add(dr);
SomeDbCommandBuilder builder = new SomeDbCommandBuilder(da);
builder.GetInsertCommand();
DataRow[] rows = ds.Tables[0].Select("", "", DataViewRowState.Added);
da.Update(rows);
The .NET DataRow will automatically try to cast your value to the target type. The following code runs fine, even though the column type is int
However adding an incorrect value will yield an exception
EDIT:
For sql types that have a parse method you can use reflection. Some types like SqlString, dont require manual parsing and can be handled by the DataRow