C# 将文本框值动态转换为表列的数据类型值

C# 将文本框值动态转换为表列的数据类型值,c#,winforms,casting,C#,Winforms,Casting,我正在尝试构建基于用户选择的动态查询,例如,我的数据库结构如下所示: columnname datatype productid int productname varchar(100) updatedate datetime lastsaledate datetime 我有一个组合框,可以动态加载表名。如果选择了一个特定的表,所有列的名称都将生成listbox,然后用户将根据自己的要求选择列,并将数据导出到excel。有时,他可能会尝试通过选择列并输入列的值来检索数据

我正在尝试构建基于用户选择的动态查询,例如,我的数据库结构如下所示:

columnname  datatype
productid     int
productname   varchar(100)
updatedate    datetime
lastsaledate  datetime
我有一个组合框,可以动态加载表名。如果选择了一个特定的表,所有列的名称都将生成listbox,然后用户将根据自己的要求选择列,并将数据导出到excel。有时,他可能会尝试通过选择列并输入列的值来检索数据

我的问题是,由于我的sql查询是基于用户选择动态构建的,有时他可能会选择productid来检索所有产品,然后数据类型是int,那么我的sql查询应该像这样构建

select * from products where productid= @pid
由于@pid值是从textbox提供的,所以我将得到错误数据类型不匹配或其他信息。如何动态转换为所选列的数据类型

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;
    }

如果要将字符串转换为int,可以按如下方式转换:

string value = "10";
int result = Convert.ToInt32(value);//value is what you want to convert
bool result = Int32.TryParse(value, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
}
//            if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           value == null ? "<null>" : value);
}
如果值转换失败,您将得到一个需要处理的异常。或者你可以像这样使用TryParse:

string value = "10";
int result = Convert.ToInt32(value);//value is what you want to convert
bool result = Int32.TryParse(value, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
}
//            if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           value == null ? "<null>" : value);
}
bool result=Int32.TryParse(值,输出编号);
如果(结果)
{
WriteLine(“将{0}转换为{1}.”,值,数字);
}
其他的
}
//如果(值==null)值为“”;
WriteLine(“尝试转换“{0}”失败。”,
值==null?“:值);
}

这些方法适用于所有数据类型。

如果要将字符串强制转换为int,可以按如下方式强制转换:

string value = "10";
int result = Convert.ToInt32(value);//value is what you want to convert
bool result = Int32.TryParse(value, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
}
//            if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           value == null ? "<null>" : value);
}
如果值转换失败,您将得到一个需要处理的异常。或者你可以像这样使用TryParse:

string value = "10";
int result = Convert.ToInt32(value);//value is what you want to convert
bool result = Int32.TryParse(value, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
}
//            if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           value == null ? "<null>" : value);
}
bool result=Int32.TryParse(值,输出编号);
如果(结果)
{
WriteLine(“将{0}转换为{1}.”,值,数字);
}
其他的
}
//如果(值==null)值为“”;
WriteLine(“尝试转换“{0}”失败。”,
值==null?“:值);
}

这些方法适用于所有数据类型。

查找类型

要将字符串转换为具有类型名称的目标类型,如果您使用的是完整类型名称,如
System.string
System.Int32
,则只需使用。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
如果您不使用完整的类型名,并且使用友好的类型名,如
string
int
,则可以创建类型字典,并从字典中按名称获取类型,例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
将字符串值转换为目标类型

可以使用方法将值更改为转换类型。当值不能转换为目标类型时,还应处理可能的
FormatException
。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
向命令添加参数

您可以使用方法将参数添加到命令的
parameters
集合中,并传递参数名和从字符串转换的值。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
注意


如果您想像问题的最后一个代码部分(存在SQL注入漏洞)一样继续使用字符串连接创建查询,则不需要进行任何类型转换,因为您将只使用字符串值,例如
“Id=1”
是使用
“Id=”+textBox1.Text创建的,不需要进行类型转换。但我强烈建议停止使用字符串连接创建查询。

查找类型

要将字符串转换为具有类型名称的目标类型,如果您使用的是完整类型名称,如
System.string
System.Int32
,则只需使用。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
如果您不使用完整的类型名,并且使用友好的类型名,如
string
int
,则可以创建类型字典,并从字典中按名称获取类型,例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
将字符串值转换为目标类型

可以使用方法将值更改为转换类型。当值不能转换为目标类型时,还应处理可能的
FormatException
。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
向命令添加参数

您可以使用方法将参数添加到命令的
parameters
集合中,并传递参数名和从字符串转换的值。例如:

var type  = Type.GetType("System.Int32");
var types = new Dictionary<string, Type>();
types.Add("bool", typeof(bool));
types.Add("int", typeof(int));
types.Add("string", typeof(string));
//and so on for byte, short, long, float, double, decimal, ...
var value = Convert.ChangeType("1", type);
command.Parameters.AddWithValue("@Id", value);
注意


如果您想像问题的最后一个代码部分(存在SQL注入漏洞)一样继续使用字符串连接创建查询,则不需要进行任何类型转换,因为您将只使用字符串值,例如
“Id=1”
是使用
“Id=”+textBox1.Text创建的,不需要进行类型转换。但我强烈建议停止使用字符串连接创建查询。

类似于var type=type.GetType(label1.text)的东西;我尝试了这种转换,但是“type”总是空的,就像您正在寻找的一样,啊,不……我正在从表模式中动态读取列的数据类型,并根据用户选择构建查询。对于查询的where子句,我必须将在textbox中收集的值传递给我的where子句,因为用户可以选择带有int或varchar或datetime的列。应将textbox值转换为适合列类型。这正是我想要的,如果你知道应该是什么类型的话?有什么问题?您总是从文本框中获取字符串。那么,为什么知道目标类型就不能将字符串转换为它呢?int.Parse(str)或float.Parse(str)?int和Parse应该由我的标签值决定,如果label.text=int,那么转换类型应该是“int”。Parse(str)如果label.text=float,那么转换类型应该是“float”。Parse(str)…etcsomething类似于var type=type.GetType(label1.text);我尝试了这个转换,但是“type”总是空的,就像你在寻找的一样,啊,不……我正在动态读取数据类型