programing tip

데이터 테이블에 null 값이 있는지 확인하는 가장 좋은 방법

itbloger 2020. 9. 21. 07:25
반응형

데이터 테이블에 null 값이 있는지 확인하는 가장 좋은 방법


데이터 테이블에 null 값이 있는지 확인하는 가장 좋은 방법은 무엇입니까?

대부분의 경우 시나리오에서 하나의 열은 모두 null 값을 갖습니다.

(이 데이터 테이블은 타사 응용 프로그램에서 반환됩니다. 응용 프로그램이 데이터 테이블을 처리하기 전에 유효성 검사를 시도하고 있습니다.)


열의 값을 값과 비교하여 DBNull.Value적합하다고 생각되는 방식으로 null 값을 필터링하고 관리합니다.

foreach(DataRow row in table.Rows)
{
    object value = row["ColumnName"];
    if (value == DBNull.Value)
        // do something
    else
        // do something else
}

DBNull 클래스에 대한 추가 정보


테이블에 null 값이 있는지 확인하려면 다음 방법을 사용할 수 있습니다.

public static bool HasNull(this DataTable table)
{
    foreach (DataColumn column in table.Columns)
    {
        if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
            return true;
    }

    return false;
}

다음과 같이 작성할 수 있습니다.

table.HasNull();

foreach(DataRow row in dataTable.Rows)
{
    if(row.IsNull("myColumn"))
        throw new Exception("Empty value!")
}

행과 열을 반복해서 던지고, null을 확인하고, bool이있는 null이 있는지 추적 한 다음 테이블을 반복 한 후 확인하고 처리 할 수 ​​있습니다.

//your DataTable, replace with table get code
DataTable table = new DataTable();
bool tableHasNull = false;

foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        //test for null here
        if (row[col] == DBNull.Value)
        {
            tableHasNull = true;
        }
    }
}

if (tableHasNull)
{
    //handle null in table
}

You can also come out of the foreach loop with a break statement e.g.

//test for null here
if (row[col] == DBNull.Value)
{
    tableHasNull = true;
    break;
}

To save looping through the rest of the table.


I will do like....

(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))

DataTable dt = new DataTable();
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["Column_Name"] == DBNull.Value)
            {
                //Do something
            }
            else
            {
                //Do something
            }
        }

You can null/blank/space Etc value using LinQ Use Following Query

   var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                  where dr1["Columnname"].ToString() == ""
                                  || dr1["Columnname"].ToString() == ""
                                   || dr1["Columnname"].ToString() == ""
                                  select Columnname);

Here Replace Columnname with table column name and "" your search item in above code we looking null value.

참고URL : https://stackoverflow.com/questions/4604414/best-way-to-check-if-a-data-table-has-a-null-value-in-it

반응형