I am trying to build dynamic query which will built on user selection for example my database structure is like below:
columnname datatype
productid int
productname varchar(100)
updatedate datetime
lastsaledate datetime
i have a combobox which will load table names dynamically. if a particular table is selected all the columns names will be generated to listbox, then user will select columns based on his requirement and export the data to excel. some times he may try to retrieve data based on selecting the column and entering the value for the column.
My problem is as my sql query is building dynamically based on user selection, sometimes he may select productid to retrieve all the products then the datatype is int then my sql query should build like
select * from products where productid= @pid
as @pid value is supplied from textbox i will get error datatype mismatch or something. how to dynamically convert to the datatype of the selected column.
var type = Type.GetType(label2.Text);
queryCmd += " WHERE " + comboBox2.SelectedItem.ToString() + "=" + Convert.ChangeType(textBox1.Text, type);
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}