【发布时间】:2016-02-01 08:49:54
【问题描述】:
我正在尝试构建基于用户选择的动态查询,例如我的数据库结构如下:
columnname datatype
productid int
productname varchar(100)
updatedate datetime
lastsaledate datetime
我有一个可以动态加载表名的组合框。如果选择了一个特定的表,所有的列名都将生成到列表框中,然后用户将根据他的要求选择列并将数据导出到 Excel。有时他可能会尝试根据选择列并输入列的值来检索数据。
我的问题是因为我的 sql 查询是根据用户选择动态构建的,有时他可能会选择 productid 来检索所有产品然后数据类型是 int 然后我的 sql 查询应该像这样构建
select * from products where productid= @pid
因为@pid 值是从文本框提供的,我会得到错误数据类型不匹配或其他东西。如何动态转换为所选列的数据类型。
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;
}
【问题讨论】:
-
类似 var type = Type.GetType(label1.text);我试过这个进行转换,但“类型”总是为空
-
好像是你要找的东西stackoverflow.com/a/5054392/444149
-
啊不...我正在从表模式中动态读取列的 data_type 并根据用户选择构建查询。对于查询的 where 子句,我必须将在文本框中收集的值传递给我的 where 子句,因为用户可以选择带有 int 或 varchar 或 datetime 的列,文本框值应转换为适合列类型。这正是我正在寻找的
-
如果你知道应该是什么类型?问题是什么 ?你总是从你的文本框中得到一个字符串。那么为什么知道目标类型 - 你不能将字符串转换为它? int.Parse(str) 或 float.parse(str) ?
-
int 和 parse 应该由我的标签值决定,如果 label.text=int ,那么转换类型应该是 "int".parse(str) 如果 label.text=float,那么转换类型应该是“float”.parse(str)..etc