dynamically adding controls to a datagrid

M

MattB

Hello. I'm creating a page to edit a person's record (name address, etc)
using a DataGrid. I want the fields that can be edited to be created at
runtime based on a list of columns in web.config. This is working fine,
and I can add a control (TextBox or DropDownList) dynamically for the
user to fill in a value. This works well for just adding controls for
data entry.

Now, I want to add validators on the fly as well and it not going quite
as smoothly. I'm suing the following excerpt in the ItemDataBound event
for this DataGrid:

Dim tb As New TextBox, vld As New RequiredFieldValidator

tb.Text = Convert.ToString(e.Item.DataItem("val"))
editCell.Controls.Add(tb)
If e.Item.DataItem("req") Then
vld.ControlToValidate = FindControl(tb.ID.ToString)
vld.ErrorMessage = "Required Field!"
editCell.Controls.Add(vld)
End If

IntelliSense is flagging the FindControl part saying:

"System.Web.UI.Control" cannot be converted to string

Is this a reasonabler approach that I just need to fix the syntax of, or
am I taking the wrong approach? Any suggestions? Thanks!

Matt
 
K

Karl Seguin

Just to vld.ControlToValidated = tb.ID no need to do a FindControl on it,
you already found it :p it's tb...you created it...

You might need to use ClientId or UniqueId instead of just ID...not 100%
sure...but just a heads up...

Karl
 
M

MattB

Karl said:
Just to vld.ControlToValidated = tb.ID no need to do a FindControl on it,
you already found it :p it's tb...you created it...

You might need to use ClientId or UniqueId instead of just ID...not 100%
sure...but just a heads up...

Karl

Thanks for the reply, but I was trying FindControl because tb.ID didn't
work (Intellisense said it was ok, but it failed at runtime).

So here's the runtime errors I get for each of those suggestions:

tb.ID:
The ControlToValidate property of '' cannot be blank.

tb.UniqueID:
Unable to find control id 'dgGuest:_ctl2:_ctl0' referenced by the
'ControlToValidate' property of ''.

tb.ClientID:
Unable to find control id 'dgGuest__ctl2__ctl0' referenced by the
'ControlToValidate' property of ''.

So could it be that in adding a second control to the same cell I'm
somehow overwriting the tb control? Any other ideas?

THANKS!

Matt
 
K

Karl Seguin

You can simply use ID if you give the tb an id before adding it to the cell

dim tb as new TextBox
tb.ID = "txt"


Karl
 
M

MattB

Karl said:
You can simply use ID if you give the tb an id before adding it to the cell

dim tb as new TextBox
tb.ID = "txt"


Karl

Cool. I actually just stumbled on that myself. Thanks again!

Matt
 

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

Forum statistics

Threads
473,754
Messages
2,569,526
Members
44,997
Latest member
mileyka

Latest Threads

Top