Pregunta

I have a datatable with data in it (customer addresses). In some instances, column ADDR3 doesn't have a value and column ADDR2 does. I'm attempting to check the value of ADDR3 and if it doesn't contain a value I want to copy the value in ADDR2 to ADDR3 and then blank out ADDR2. I was trying to use the below code, but it isn't working. I placed a breakpoint after my 'if' statement, but the program never breaks. But, I know for a fact that a lot of the rows have null ADDR3 fields. Can anyone tell me what I'm doing wrong?

            foreach (DataRow row in dataSet11.DataTable1.Rows)
            {
                object value = row["ADDR3"];
                if (value == DBNull.Value)
                {
                    row["ADDR3"] = row["ADDR2"];
                    row["ADDR2"] = " ";
                }
            }
¿Fue útil?

Solución

It's likely that your row["ADDR3"] value is NEVER equal to DbNull.Value. This is often the case with data tables that were transferred over a web service, for example (there will be empty strings instead of nulls due to the XML transformations).

Put a break point BEFORE your if and find exactly what the value is. You might try checking for row["ADDR3"] == null or string.IsNullOrWhiteSpace(row["ADDR3"].ToString())

Otros consejos

Have you tried comparing the value to null (rather than DBNull.Value)? I believe DBNull.Value is exclusive for certain database objects and does not appear once read into a dataset/datatable.

Try this:

foreach (DataRow row in dataSet11.DataTable1.Rows)
{
    if (
        row.IsNull("ADDR3") // True if the value is null
        ||
        String.IsNullOrWhitespace(row["ADDR3"]) // True if the value is "", " ", etc.
       )
    {
        row["ADDR3"] = row["ADDR2"];
        row["ADDR2"] = " ";
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top