Dynamically Populate DataGrid Using SqlDataReader

Tech-Archive recommends: Fix windows errors by optimizing your registry



A SqlDataReader is populated with the records from a SQL Server 2005 DB
table. The records retrieved depends upon 2 conditions (the conditions
depend on what a user selects in an ASPX page). If condition1 is true,
then the SqlDataReader will be populated with the records existing in
table1 & will return 0 to the calling function but if condition2 is
true, then the SqlDataReader will be populated with the records from
another table named table2 & will return 1 to the calling function.

Moreover the 2 tables do not have the same no. of columns - even the
column names are different. This means that the DataGrid has to be
filled dynamically. Had this not been the case, then using the
DataField property of the DataGrid, I could have populated the DataGrid
using

<asp:DataGrid ID="dgAddress" runat="server">
<Columns>
<asp:BoundColumn DataField="Address" HeaderText="ADDRESS"/>
<asp:BoundColumn DataField="City" HeaderText="CITY"/>
<asp:BoundColumn DataField="State" HeaderText="STATE"/>
<asp:BoundColumn DataField="Country" HeaderText="COUNTRY"/>
<asp:BoundColumn DataField="Zip" HeaderText="ZIP"/>
</Columns>
</asp:DataGrid>

But since I need to populate the DataGrid dynamically, the above
approach won't be feasible. So I tried to do it in the Page_Load sub
but I don't find any property named 'DataField' when I browsed through
the different properties of the DataGrid.

So how do I populate the DataGrid dynamically?

.


Quantcast