是否有可能通过一个参数是DB.null并设置数据库等于价值? [英] Is it possible to pass a parameter that is DB.null and set a value in the database equal to that?

查看:119
本文介绍了是否有可能通过一个参数是DB.null并设置数据库等于价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库(1记录)中提取数据,并把每个值在一个文本框或DropDownList中。一些值是DB.null。如果是这样,我转换他们每个人(空白)。然而,一旦用户修改文本框/下拉列表中,他们可以拯救的新成果。我的问题是这样的:

如果用户离开空白的东西,我希望能够保持该值DB.null。有没有办法做到这一点?

此外,是有可能,如果有一个值在文本框和用户决定删除它,我也可以将其转换为DB.Null?这里就是我试图做给你们的一些想法:

 产品名称!=
    ? myCommand.Parameters.AddWithValue(@产品名称,产品名称)
    :myCommand.Parameters.AddWithValue(@产品名称,DBNull.Value);


解决方案

在SQL Server我相信你可以互换使用 DBNull.Value 来设定一个值 NULL

我也想改变你的code这样:

  myCommand.Parameters.AddWithValue(
    @产品名称,
    //这需要投为:?必须返还相同种类
    String.IsNullOrWhiteSpace(产品名称)
        ? (对象)DBNull.Value
        (对象)产品名称
);

或使用并没有进行明确的转换:

  myCommand.Parameters.AddWithValue(
    @产品名称,
    ! String.IsNullOrWhiteSpace(产品名称)?产品名称:空
);

I'm pulling data from a database (1 record) and putting each value in a textbox or dropdownlist. Some of these values are DB.null. If they are, I convert each of them to "" (blank). However, once the user has modified the textboxes/dropdown list, they can "Save" the new results. My problem is this:

If the user leaves something blank, I want to be able to maintain that the value is DB.null. Is there a way to do this?

Also, is it possible that if there is a value in a textbox and the user decides to delete it, I can also convert it to DB.Null? Here's what I tried to do to give you guys some idea:

productName != ""
    ? myCommand.Parameters.AddWithValue("@ProductName", productName)
    : myCommand.Parameters.AddWithValue("@ProductName", DBNull.Value);

解决方案

With SQL Server I believe you can interchangably use null or DBNull.Value to set a value to NULL.

I'd also change your code to this:

myCommand.Parameters.AddWithValue(
    "@ProductName",
    // this requires a cast as ?: must return the same type
    String.IsNullOrWhiteSpace(productName)
        ? (object)DBNull.Value
        : (object)productName
);

Or using null and without an explicit cast:

myCommand.Parameters.AddWithValue(
    "@ProductName",
    ! String.IsNullOrWhiteSpace(productName) ? productName : null
);

这篇关于是否有可能通过一个参数是DB.null并设置数据库等于价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆