如何循环数据集并更改数据c#

时间:2011-06-16 12:11:57

标签: c# asp.net dataset

我试图遍历数据集,哪里有0我想将其更改为空值或空白到目前为止我有这个

foreach (DataRow drRow in ds.Tables[0].Rows)
{            
     //loop through cells in that row
      {
        //if the value is 0 change to null or blank
      }
}

任何人都可以帮助我解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

不确定

foreach (DataRow drRow in ds.Tables[0].Rows)

    {
        for(int i = 0; i < ds.Tables[0].Columns.Count; i++)
        {
            int rowValue;

            if (int.TryParse(drRow[i].ToString(), out rowValue))
            {
                if (rowValue == 0)
                {
                    drRow[i] = null;
                }
            }

        }
    }

我真的相信没有人还在使用DataSet :(

答案 1 :(得分:0)

这样的事情可能有所帮助:

foreach (DataRow rows in table.Rows)
{
    object value = null;
    var cells = rows.ItemArray;
    for (int i = 0; i < cells.Length; i++)
    {
        value = cells[i];
        if (value != null && value.GetType() == typeof(int))
        {
            if ((int)value == 0)
            {
                cells[i] = null;
            }
        }
    }
    rows.ItemArray = cells;
}

答案 2 :(得分:0)

你可以做到

DataTable dt = new DataTable();
.....
.....

    DataRowCollection drColl = dt.Rows;
                for(int j=0; j<drColl.Count;j++) 
                {
                    DataRow drRow = drColl[j];
                    object[] itemArr = null;
                    itemArr = drRow.ItemArray;
                    //loop through cells in that row       
                    for(int i=0; i<itemArr.Length; i++)
                    {         
                        //if the value is 0 change to null or blank 
                        if (itemArr[i].ToString() == "0")
                            drRow[i] = "";
                    } 
                }