Reading columns in a datagrid that is nested in a repeater

  • Thread starter Thread starter Maziar Aflatoun
  • Start date Start date
M

Maziar Aflatoun

Hi everyone,

I have a datagrid that I create inside a Repeater at runtime. I have
defined a checkbox beside each row so that users can select multiple rows.
<asp:datagrid id="dgProducts" HorizontalAlign="Center"
AutoGenerateColumns="false" CellPadding="2"
runat="server" >
......
<asp:TemplateColumn HeaderText="" HeaderStyle-Width="20">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<asp:CheckBox ID="cbxProduct" Runat="server"
AutoPostBack="False"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>

Just below my datagrid I have a button (Add button). I want to read the
values of all the checkboxes in my dynamically created datagrid. But it
keeps complaining that

System.NullReferenceException: Object reference not set to an instance of an
object.
for that Line Response.Write...

This is the code
private void btnAddProducts_Click(object sender, System.EventArgs e)
{
DataGrid dgProducts = this.Page.FindControl("dgProducts") as DataGrid;
Response.Write("Rows: " + dgProducts.Items.Count);
}

Can someone please help me with this?

Thank you
Maz
 
wrong name FindControl("dgProducts") : name (and ids) must be reasonably
unique and are thus :
- prefixed by the name of the parent container.
- suffixed by a number

you will have to iterate through the object hierarchy looking for objects
whose id includes "cbxProduct"
 
Isn't dgProducts unique? Can you please show me an example? (Prefixed by the
name of the parent container and suffixed by a number)? Is there an easier
way to do this?

Thanks
Maz.
 
Hi Maz,

No, it’s in the Repeater, so it’s not unique.
You should use repeater.Items[index].FindControl("dgProducts").

HTH

Elton Wang
(e-mail address removed)
 
Back
Top