Click here to Skip to main content
15,867,997 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a dataset named dbset and it has one DataTable.

when i fill this dataset, there is some column, has no value. I want to set default value O if the column type is numeric otherwise default value will "no data".

please help me to write this code.

i want to use this kind of approach ..

int rowcount = dataSet2.Tables[0].Rows.Count;

        for (int i = 0; i < rowcount; i++)
        {
            dataSet2.Tables[0].Columns[i]...............

        }
Posted
Comments
King Fisher 27-Mar-14 5:47am    
better you use isnull(column,0) function in Query.
sachi Dash 27-Mar-14 5:54am    
no... there is a problem ! thats why i write it through code.

Can you try this instead of your for loop

Edit:
C#
foreach (DataRow row in dataSet2.Tables[0].Rows)
{
    foreach (DataColumn col in dataSet2.Tables[0].Columns)
    {
        if (row[col] == null)
        {
            if(row[col].GetType() == typeof(int)){
                row[col] = 0;
            }
            if (row[col].GetType() == typeof(string))
            {
                row[col] = "no data";
            }
        }
    }
}

this code will iterate all the cells in your dataset



Old
C#
foreach (DataRow row in dataSet2.Tables[0].Rows)
{
   if (row["colName"] == null)
   {
       row["colName"] = 0;
   }
   if (row["colName2"] == null)
   {
       row["colName2"] = "no data";
   }
}
 
Share this answer
 
v3
Comments
sachi Dash 27-Mar-14 5:53am    
i need a dynamic way to represent column..... when i don't know the "columnname".
BELGIUMsky 27-Mar-14 6:04am    
Maybe the new solution is better for you
Let me know if it works fo you
Alternatively you can set the default value to the datatable

Example:

DataTable dt = new DataTable();

dt.Columns.Add("Country",typeof(String));
dt.Columns["Country"].DefaultValue = "India";
 
Share this answer
 
Comments
BELGIUMsky 27-Mar-14 6:07am    
This only works for new added rows
if i remember correctly
There are two ways to achieve this:

1. You can iterate the DataTable object and check the value of each column using below code:

C#
foreach (DataRow row in dt.AsEnumerable())
{
   foreach (DataColumn col in dt.Columns)
   {
      if (row.IsNull(col))
      {
         if (row[col].GetType().Equals(typeof(int)))
            row[col] = 0;
         else if(row[col].GetType().Equals(typeof(string)))
            row[col] = "No Data";
      }
   }
}


2. In the sql query we can check this :

SQL
ISNULL(col,0)  -- for number type
ISNULL(col, '') -- for string type


Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900