1

我有一个返回几列的存储过程,我只对构建一个ProjectID值为 null 的 gridview 感兴趣。我下面的代码返回所有列的所有行,它只是应该返回 where column = projectID。有人可以看看它。谢谢

DataRowCollection rowCollection = spDataTable.Rows;
DataTable dt = new DataTable();

foreach (DataColumn col in spDataTable.Columns)
{
                if (col.ColumnName == "ProjectID")
                {
                    dt.Columns.Add(col.ColumnName);
                    lb_Test.Items.Add(col.ColumnName);
                        foreach(DataRow ros in col.Table.Rows)
                        {
                            foreach (object oObj in ros.ItemArray)
                            {
                                if (oObj != null)
                                {
                                    if (col.ColumnName == "ProjectID")
                                    {
                                        lb_Test.Items.Add(oObj.ToString());
                                        dt.Rows.Add(oObj);
                                    }
                                }
                                else
                                {
                                    lb_Test.Items.Add("Null");
                                }
                            }   
                        }
                        grd_test.DataSource = dt;
                        grd_test.DataBind();
                }
                else
                {
                    lb_Test.Items.Add("Not valid Name");
                }
}
4

1 回答 1

1

如果我理解这个问题,似乎你所需要的就是这个......

DataRowCollection rowCollection = spDataTable.Rows; 
DataTable dt = new DataTable(); 

foreach(DataRow dr in spDataTable.Rows)
{
        object projectId = dr["ProjectID"];
        if (projectId == null)
        {
            dt.Rows.Add(dr);
        }
     }

这将使用 ProjectID 列中的值为空的所有行填充 rowCollection。

话虽如此,如果可以的话,您可以考虑将存储过程更改为只返回您想要的行。这将节省网络流量。

Also, a DataTable has built-in filtering capabilities...http://msdn.microsoft.com/en-us/library/zk13kdh0(v=vs.71).aspx. Maybe this would be a better approach.

DataViews also have the capability to filter data. Then you can bind your GridView to a DataView... https://stackoverflow.com/questions/10893860/how-to-filter-gridview-from-textbox

There are several ways to filter DataTables that are built into .Net. There is no need to roll your own.

于 2012-10-10T18:40:17.040 回答