Reference "Programmatic" Gridview Control on Postback

J

John Walker

Hi, my gridview has a label field which I'm replacing with a dropdownlist at
the time of databind with this code:

Dim lblType As Label = CType(e.Row.FindControl("lbltype"), Label)
e.Row.Cells(Cnst.Cells.AccountType).Controls.Remove(lblType)

Dim ddlType As New DropDownList
ddlType.ID = "ddlType"
ddlType.Items.Add(New ListItem("test", "test"))
ddlType.Items.Add(New ListItem("Bill To", "BILLTO"))
ddlType.Items.Add(New ListItem("Acct Of", "ACCTOF"))
e.Row.Cells(Cnst.Cells.AccountType).Controls.Add(ddlType)


So, the dropdown displays in the browser, but on subsequent postbacks i
cannot reference that control:

Dim ddlType As DropDownList =
CType(gvr.Cells(Cnst.Cells.AccountType).FindControl("ddlType"), DropDownList)

gvr is the gridviewrow and the value of the dropdownlist is returning
"Nothing".... but when i'm not creating the dropdown programatically i am
able to reference it successfully.

What am i doing wrong??

Thanks,
John
 
P

Peter Bucher [MVP]

Hello John

You add the DDL in the RowDataBound Event, right?
And the following Code is in your Page_Load Method:
Dim ddlType As DropDownList =
CType(gvr.Cells(Cnst.Cells.AccountType).FindControl("ddlType"),
DropDownList)

right?

If so, move the above Code in Page_PreRender, cause at that time
the RowDataBound Event should be done and you`ve access to your
created Control at RowDataBound Time.
 
J

John Walker

Peter,
Yes i add the DDL on the RowDataBound event, but i do not attempt the
"FindControl" until the page has already been displayed to the screen and the
user clicks "Save" (after changing the selected value in the dropdownlist.)
So, i am doing the FindControl in the button click event. Please take
another look and let me know if i'm doing anything wrong when/where creating
the dropdown.
As i said, when defining the ddl in aspx (instead of creating it
programmatically) the FindControl works successfully.
Thanks!
John
 
P

Peter Bucher [MVP]

Hi John
Yes i add the DDL on the RowDataBound event, but i do not attempt the
"FindControl" until the page has already been displayed to the screen and
the
user clicks "Save" (after changing the selected value in the
dropdownlist.)
Primarily you should add the Controls at least at Page_Load, better OnInit
of the Lifecycle.
That means in your case, that you should define your DropDownList in a
TemplateField for example.

This way, you`ve the possibility to switch the "Visible" Property of your
Control at any time in the Cycle (at least OnPreRender of the Page).

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top