How to define a DataType column in DataTable?
I have a requirement to store the some data in a datatable. The columns in the table are: -ID -Text -Value -DataType How should I define the table columns so that the DataType column stores native and composite types?
Currently I am storing it as
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("Text", typeof(string)));
dt.Columns.Add(new DataColumn("Value", typeof(string)));
dt.Columns.Add(new DataColumn("DataType", typeof(string)));
Later in my program I am trying to parse the values and开发者_开发技巧 depending on the datatype I show the control. Like, if the datatype is int then show textbox, if bool then show dropdown.
I am sure there will be an easier way to do this. Please suggest how to achieve this functionality? Example code will help me in understanding it better. Thanks!
Creating columns like DataType and Value in a DataColumn
or DBMS is usually symptomatic of the Inner-platform effect, where you try to create a typed database inside your typed database by ignoring the type definitions in your database.
Don't do that. DataColumn
s already support typed data, querying the schema, and joining tables that contain heterogeneous data. Store ints as ints , booleans as booleans, and you won't have to parse anything. You can determine the data type of a DataColumn
with:
var dc = new System.Data.DataColumn("ID", typeof(int));
bool isInt = dc.DataType.Equals(typeof(int));
You can make the code a little easier by doing the following:
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Text", typeof(string));
dt.Columns.Add("Value", typeof(string));
dt.Columns.Add("DataType", typeof(string));
There is no need to use the datacolumn constructor.
So, you are really creating some sort of authoring tool. You define your datatypes in a database and then, create the controls on the fly when then data is read?
Ok, so rather than store the default values (true, false) in the database, what about storing them in the controls. For example you now a checkbox must have default values of true/false, A txtbax has default values of blank etc.
Or, yu could extend your database to hold a list of possible values for a field. By that I mean you might have a row that reads
Id=5, Text='Selected'. Value='False', Type='System.Boolean'
Then in another table
Id=5, Value=True, default=false Id=5, Value=false, default=true
or, for a string
Id=5, Text='Selected'. Value='UK', Type='System.Text'
Id=5, Value='UK', default=true id=5, value='USA', default=false
If you do this, then you can drop the value from the first table..
Not totally sure that helps?
精彩评论