【问题标题】:type cast textbox value dynamically to the data type value of a table column将文本框值动态类型转换为表列的数据类型值
【发布时间】: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

标签: c# winforms casting


【解决方案1】:

查找类型

要将字符串转换为具有类型名称的目标类型,如果您使用像System.StringSystem.Int32 这样的完整类型名称,您可以简单地使用Type.GetType(typeName)。例如:

var type  = Type.GetType("System.Int32");

如果您没有使用完整的类型名称,而是使用友好的类型名称,例如 stringint,您可以创建一个类型字典并通过其名称从字典中获取类型,例如:

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 type = types["int"];

将字符串值转换为目标类型

您可以使用Convert.ChangeType(value, conversionType) 方法将值更改为转换类型。当值不能转换为目标类型时,您还应该处理可能的FormatException。例如:

var value = Convert.ChangeType("1", type);

为命令添加参数

您可以使用AddWithValue (parameterName, value) 方法将参数添加到您的命令的Parameters 集合,并传递参数名称和您从字符串转换的值。例如:

command.Parameters.AddWithValue("@Id", value);

注意

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

【讨论】:

  • 你说得对,我在这上面浪费了 1 小时,在构建查询时不需要类型转换。我知道构建查询会导致 sql 注入。谢谢你的建议
【解决方案2】:

如果您想将字符串转换为 int,您可以像这样进行转换:

string value = "10";
int result = Convert.ToInt32(value);//value is what you want to convert

如果值转换失败,您将收到需要处理的异常。或者你可以像这样使用 TryParse:

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

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

【讨论】:

  • 我应该得到我的 label1.text 的程序集限定名称,它存储 int 或 bit 或 datetime 或任何东西..你知道怎么做
  • 我不确定我是否理解您的要求。但是您可以使用上面的示例将 Label1.Text 的内容转换为您想要的任何数据类型(如果可以转换)。如果无法进行强制转换,您将不得不编写代码来处理它。
  • 我正在发布我的屏幕,然后你就会明白我的要求
  • 你能检查我是否添加了图片
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
相关资源
最近更新 更多