Search code examples
c#visual-studio-2010datatabledatacolumn

I can't seem to check a value in a particular column of a datatable. Why?


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"] = " ";
                }
            }

Solution

  • 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())