如果任何列返回null值,如何设置默认值0或字符串? [英] How can set a default value 0 or string if any column return null value?
本文介绍了如果任何列返回null值,如何设置默认值0或字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为dbset的数据集,它有一个DataTable。
当我填充此数据集时,有一些列,没有任何价值。如果列类型为数字,我想设置默认值O,否则默认值为无数据。
请帮我写这段代码。
i想要使用这种方法..
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]...............
}
推荐答案
你可以试试这个而不是你的for循环< br $>
编辑:
Can you try this instead of your for loop
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
foreach (DataRow row in dataSet2.Tables[0].Rows)
{
if (row["colName"] == null)
{
row["colName"] = 0;
}
if (row["colName2"] == null)
{
row["colName2"] = "no data";
}
}
或者你可以设置数据表的默认值
示例:
DataTable dt = new DataTable();
dt.Columns。添加(Country,typeof(String));
dt.Columns [Country]。DefaultValue =India;
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";
有两种方式实现这个目标:
1.您可以使用以下代码迭代DataTable对象并检查每列的值:
There are two ways to achieve this:
1. You can iterate the DataTable object and check the value of each column using below code:
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.在sql查询中我们可以检查:< br $> b $ b
2. In the sql query we can check this :
ISNULL(col,0) -- for number type
ISNULL(col, '') -- for string type
谢谢
Thanks
这篇关于如果任何列返回null值,如何设置默认值0或字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文