I came across a very strange behavior in asp.net's ObjectDataSource
, the description to reproduce is somewhat long, so bear with me while I set the scene.
So, imagine a trivial ObjectDataSource/GridView combo in a User Control. The ObjectDataSource calls a method which returns a List
of objects, and the GridView shows these objects in tabular form:
<div runat="server" ID="ControlWrapper">
<asp:GridView ID="GridView1" AutoGenerateColumns="true" DataSourceID="ObjDataSource1" OnRowDataBound="GridView1_RowBound" runat="server">
</asp:GridView>
</div>
<asp:ObjectDataSource ID="ObjDataSource1" runat="server" SelectMethod="GetBundle" OnSelecting="FixDataSource_Selecting" OnSelected="FixDataSource_Selected"
TypeName="West.VitalSigns.Contracts.ProdFixController">
</asp:ObjectDataSource>
This approach will work with pretty much nothing in the code-behind. But let's say that we want to create n number of GridView
-s depending on the contents of the database. So we comment out the GridView in the markup...
<div runat="server" ID="ControlWrapper">
<!--
<asp:GridView ID="GridView1" AutoGenerateColumns="true" DataSourceID="ObjDataSource1" OnRowDataBound="GridView1_RowBound" runat="server">
</asp:GridView>
-->
</div>
...and add something like this to the ObjectDataSource's Selected
event handler:
protected void FixDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs args)
{
HashSet<string> components = new HashSet<string<()
foreach (ProdFix fix in (List<ProdFix>)args.ReturnValue)
{
if (!components.Contains(fix.Component))
{
GridView v = new GridView();
v.ID=fix.Component.Replace(" " ,"").Replace("-","");
v.AutoGenerateColumns = true;
v.DataSource = args.ReturnValue;
v.RowDataBound +=new GridViewRowEventHandler(BundleGrid_RowBound);
ControlWrapper.Controls.Add(v);
components.Add(fix.Component);
}
}
}
This code works (or at least the un-simplified version works on my machine), so you decide to remove the commented-out section from the markup (don't want that cruft hanging around, after all!)
<div runat="server" ID="ControlWrapper">
</div>
When you do this, however, the code no longer works! The ObjectDataSource won't fire, which means that the Selected
event will never happen, which means you won't get your GridView
-s. It looks like ObjectDataSource is reacting to commented-out markup in the aspx file?
So, is this:
- A bug in ASP.NET?
- A non-standard way of dynamically creating GridViews?
- A WTF that I shouldn't have tried anyway?
- All of the above?