我正在使用VS2015和C#。
在我的网络应用中,我动态创建了几个GridView。在运行时创建的GridView数量取决于数据(因此可以是1或2或任何否)。
所以它在循环中。我想将DataSourceObject
作为数据源分配给每个GridView,如:
i=1;
DataRow Myrow;
foreach (DataRow row in dtSection.Rows)
{
Myrow = row;
GridView grid = new GridView();
grid.id = "grid" + i;
grid.datasource = "data" + i;
ObjectDataSource dataSource = new ObjectDataSource();
dataSource.ID = "data" + i;
dataSource.SelectMethod = "GetTable";
dataSource.TypeName = "MyNameSpace.MyClass";
i = i + 1;
}
我的GetTable
方法,它返回DataTable作为每个网格的数据源:
public DataTable GetTable()
{
DataTable dtpage = new DataTable();
dtpage = ReportDataTable.Clone(); // My another data table from which I am selecting few rows
DataRow[] rowArray = ReportDataTable.Select("title = '" + Myrow[0].ToString() + "'");
foreach (DataRow row1 in rowArray)
{
dtpage.ImportRow(row1);
}
return dtpage;
}
对我而言,它无法正常工作。 GetTable
方法在第一个循环完成后执行,即在创建所有网格之后执行。所以当它最终执行时,方法Myrow
为null并且它给出了null异常。
如何实现它,以便正确分配,如:
grid1.datasource = data1, grid2.datasource = data2 .... etc
答案 0 :(得分:0)
解决了它:)
为ObjectDataSource添加了选择参数。
现在它为我工作。
foreach (DataRow row in dtSection.Rows)
{
Myrow = row;
GridView grid = new GridView();
grid.id = "grid" + i;
grid.datasourceid = "data" + i;
ObjectDataSource dataSource = new ObjectDataSource();
Parameter pm = new Parameter();
pm.Type = TypeCode.String;
pm.Name = "title";
pm.DefaultValue = row[0].ToString();
dataSource.ID = "data" + i;
dataSource.SelectMethod = "GetTable";
dataSource.SelectParameters.Clear();
dataSource.SelectParameters.Add(pm);
dataSource.TypeName = "InternalAuditInspection.ManageGraphReport";
dataSource.Select();
dataSource.DataBind();
i = i+1;
}
public DataTable GetTable(String title)
{
DataTable dtpage = new DataTable();
dtpage = ReportDataTable.Clone();
DataRow[] rowArray = ReportDataTable.Select("title ='"+ title + "'");
foreach (DataRow row1 in rowArray)
{
dtpage.ImportRow(row1);
}
return dtpage;
}