Dynamically created control in Datagrid problem

E

Elton Wang

Hi Wanky,

You can use

datagrid.Items(rowIndex).Cells(colIndex).Contrls(0[or 1))

to get the reference.

Or you can assign ID to a control when you add it, so late
you can get it.

BTW, it's better to add control in ItemCreated event.

HTH

Elton Wang
(e-mail address removed)
 
E

Elton Wang

Followng code snippet shows how to loop thru datagrid
items (rows) to get control reference:

Dim ctrl As Control
For Each item As DataGridItem In datagrid.Items
ctrl = item.Cells(4).Controls(0) ' or try Controls(1)
depending on how to you add it
' If you assign ctrl ID, you can
ctrl = item.FindControl("ctrlID")

Dim ctrlType As String = item.Cells(2).Text
If ctrlType.Equals("Textbox") Then
Dim txtBox As TextBox = CType(ctrl, TextBox)
' Process as text box
Else
Dim ck As CheckBox = CType(ctrl, CheckBox)
' process as checkbox
End If

' Or you can dynamically find control type
If TypeOf ctrl Is TextBox Then
Dim txtBox As TextBox = CType(ctrl, TextBox)
' Process as text box
Else
Dim ck As CheckBox = CType(ctrl, CheckBox)
'process as checkbox
End If
Next

HTH

Elton Wang
(e-mail address removed)
 
E

Elton Wang

I prefer to use same ID for both TextBox and CheckBox, so
it is easy to get control first then to figure out what
kind control it is. And it's better to use For Each loop
rather than For index loop.

HTH

Elton
 
E

Elton Wang

I'm not sure what causes the problem. It might be that
the .NET can't save dynamically created control data after
data binding in viewstate (I just guess.). If that, you
can statically add both TextBox and Checkbox (given
different id, i.e. txtID, ckID) in cell(4), then when in
ItemDataBound, set one invisible accordingly. In your
GetValues method,
using
If ctlType.Equals("Textbox") Then
Dim tb As TextBox = CType(dg.FindContrl("txtID"),
TextBox)
Else
Dim cb As CheckBox = CType(dg.FindContrl("ckID"),
CheckBox)
End If

HTH

Elton Wang
 
E

Elton Wang

I don't think there are big problems to get solution. In
one way or another we can find a means to get the
reference of the control when the page is postback.
 

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,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top