How do I access control on edit item template in DataView control?

I have a DataView control. I have a Template Field named MyNewTemplateField and in it's Edit Items Template I have a text box called "txtMyTextBox", which I want to do something with the data typed in, and then take that result and put it in the Access database.

 

    Protected Sub DataView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles dvAcct.ItemCommand
        Select Case e.CommandName
            Case "Edit"
                Dim txtTheText As New TextBox
                txtTheText = DataView1.FindControl("txtMyTextBox")
                txtTheText.Text = "hello"

        End Select
    End Sub

 
ok, I get an error on txtTheText.Text = "hello" saying I have to use "New" to create a new instance. Looking at the txtTheText, it is set to "nothing" by the time it gets to the "hello" line. This means it didn't find the control?

How do I get it to find the control?


 

0
FuzzieDice
1/23/2007 1:59:53 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

17 Replies
1268 Views

Similar Articles

[PageSpeed] 55
Get it on Google Play
Get it on Apple App Store

I meant DetailsView control, not DataView. Sorry.
0
FuzzieDice
1/23/2007 2:28:29 AM

Hi, FuzzieDice: 

Do you use use a DetailsView? I have not seen the DataView as the control in the Tool Box.

If so, you can try to set the RowState of the particular row to Edit adn then you can use FindControl to access the controls in the EditTemplate.


Best Regards,
__________________________________________________
Sincerely,
Rex Lin
Microsoft Online Community Support

If there is any question or the issue is not resolved, please feel free to mark the thread as not resolved
0
Rex
1/23/2007 2:30:58 AM

Yes, I'm using the DetailsView. Sorry about the typo.

I don't understand what you're saying at all. I can't find the control. It's already in Edit mode as shown in my code above so I don't know what you mean by setting it as it's already editing the field. I need to figure out how to get the information out of the textbox. It doesn't show up in the properties unless I'm in design mode and editing the EditTemplate. Then it shows up as:

DetailsView1.Field12MyNewTemplateField.EditItemTemplate.txtMyTextBox

But it's not in the drop down in the code view.


 

0
FuzzieDice
1/23/2007 3:02:28 AM

Yes. When you do the findcontrol in the command event, it will get the reference to the control in the ItemTemplate instead of the on in the EditTemplate. So you can try to set the RowState of this particular row and then you can use findcontrol to access your control in the EditTemplate.

this.DetailsView1.Rows[1].RowState = DataControlRowState.Edit;

// use findcontrol here/


Best Regards,
__________________________________________________
Sincerely,
Rex Lin
Microsoft Online Community Support

If there is any question or the issue is not resolved, please feel free to mark the thread as not resolved
0
Rex
1/23/2007 3:20:56 AM

That is not Visual Basic. I'm using Visual Basic.

 I tried it this way trying to figure out your C Code.

DetailsView1.Rows(12).RowState = DataControlRowState.Edit

It says that the RowState is ReadOnly. So I can not set the row state.

So this doesn't work.


 

0
FuzzieDice
1/23/2007 3:30:24 AM

I've figured it out. There was an article (now I forgot where) that said that you can't use FindControl because template controls are assigned IDs and runtime. So, you have to do this via code such as this:

 

1            If DetailsView1.CurrentMode = DetailsViewMode.Edit Then
2                For Each dvr As DetailsViewRow In dvAcct.Rows
3                    Dim intCellCount As Integer
4                    intCellCount = dvr.Cells.Count
5                    If intCellCount = 2 Then
6                        Dim intCtrlCount, i As Integer
7                        intCtrlCount = dvr.Cells(1).Controls.Count
8                        If intCtrlCount > 0 Then
9                            For i = 0 To intCtrlCount - 1
10                               Dim txt As Control
11                               Dim tpe As Type
12                               txt = dvr.Cells(1).Controls(i)
13                               tpe = txt.GetType
14                               If tpe.Name = "TextBox" Then
15                                   Dim txtBox As TextBox
16                                   txtBox = txt
17                                   Dim strText, strID As String
18                                   'Break at the end of the next two lines and hover over the str
19                                   'variables to see the contents.
20                                   strText = txtBox.Text
21                                   strID = txtBox.ID
22                               End If
23                           Next
24                       End If
25                   End If
26               Next
27           End If
  

Breakpoint at line 22 then hover over the str variables in lines 20 and 21, you'll see what is in the text boxes. This can be adapted to look at other controls. Just use if tpe.name <> "LiteralControl" in line 14 and make any necessary adjustments and tests to consider text boxes, check boxes, and the like.

Then one could add custom code and manually update the database.

One last note: It's best to go in and edit the fields, and convert them all to TemplateFields, then go into each field's EditTemplate and click on the control. Then give it a name in the ID property. This way, the txtBox.ID in line 21 won't come up as '(nothing)' and you could reference it if you need to.

 

0
FuzzieDice
1/23/2007 5:10:51 AM
FuzzieDice:

template controls are assigned IDs and runtime.

Should read:

template controls are assigned IDs at runtime.

 I wish there was a way to edit our posts in this forum. Tongue Tied


 

0
FuzzieDice
1/23/2007 5:14:19 AM

Ok, I've cleaned up the code a little bit and made it a function which you can use in any dataview control:

 

    'Get Data From DetailsView
    Public Function GetDetailsViewData(ByVal dvControl As DetailsView) As ArrayList
        Dim arrData As New ArrayList

        For Each dvr As DetailsViewRow In dvControl.Rows
            If dvr.Cells.Count = 2 Then
                If dvr.Cells(1).Controls.Count > 0 Then
                    For Each ctrlControl As Control In dvr.Cells(1).Controls
                        Select Case ctrlControl.GetType.Name
                            Case "TextBox"
                                Dim txtBox As TextBox
                                txtBox = ctrlControl
                                arrData.Add(Trim(txtBox.Text))
                            Case "CheckBox"
                                Dim chkBox As CheckBox
                                chkBox = ctrlControl
                                arrData.Add(chkBox.Checked.ToString)
                            Case "DropDownList"
                                Dim cmbBox As DropDownList
                                cmbBox = ctrlControl
                                arrData.Add(cmbBox.SelectedValue)
                        End Select
                    Next
                End If
            End If
        Next

        Return arrData

    End Function

To use it, just do the following:

 

    Protected Sub DataView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataView1.PreRender
        If DataView1.CurrentMode = DetailsViewMode.Edit Then
            'Get Data
            Dim arrData As New ArrayList
            arrData = sMod.GetDetailsViewData(DataView1)
        End If
    End Sub
  

 

0
FuzzieDice
1/23/2007 7:33:03 AM

Ok, I have been fiddling with it some more and I have now finally got a subroutine that let's you access and return the actual control! :)

Here's the steps:

1. In your details view, edit the cells and make every one of them which you need to access - convert to template.

2. Now edit the template for item and edit item. Click on the controls and give them names you can remember (write them down, is best or type in a text editor and print them out for reference). This is important as you'll need these names to access the controls.

3. Add this code to your project either as a separate class or in your page as a separate function:

 
    Public Function DVFindControl(ByVal dvControl As DetailsView, ByVal strControlID As String) As Control

        Dim ctlTarget As New Control

        For Each dvr As DetailsViewRow In dvControl.Rows
            If dvr.Cells.Count = 2 Then
                If dvr.Cells(1).Controls.Count > 0 Then
                    For Each ctrlControl As Control In dvr.Cells(1).Controls
                        If ctrlControl.GetType.Name <> "LiteralControl" Then
                            If ctrlControl.ID = strControlID Then
                                ctlTarget = ctrlControl
                                Return ctlTarget
                            End If
                        End If
                    Next
                End If
            End If
        Next

        Return ctlTarget

    End Function

 4. Use this function in your program:

 

Dim EControl As New Control
Dim EtxtBox As New TextBox ' Or whatever control you are accessing
EControl = DVFindControl(DetailsView1, "txtMyTextBox")
EtxtBox = EControl

 5. Now you can access the control just like you would any other, ie: txtMyTextBox.Text, etc.

But there you have it. This will work on any control you need to find embeded somewhere in the DetailsView. 

Warning: (Yes, there has to be one of those too). Be very sure that you are in the right view mode! The access code probably should be put in your DetailsView's PreRender event. Otherwise it won't find the control.

I hope that this will help others that run into this problem. Thank you to those who replied as it did give me some starting points.

0
FuzzieDice
1/25/2007 2:45:03 AM

How could I get this to work for a GridView?

 

Kind Regards,

 

James 

0
jamesmbradley
1/29/2007 11:57:58 PM

You're in luck. :) Here's my routine that I use for GridView controls. It's a bit different since GridViews are a little different:

 This returns the control, as does my last example, so you can directly access the control the same way when the control is returned by the function below.

 

    Public Function GVFindControl(ByVal gvControl As GridView, ByVal intRow As Integer, ByVal strControlID As String) As Control

        Dim ctlTarget As New Control

        For Each dvr As GridViewRow In gvControl.Rows
            If gvControl.Rows(intRow).Cells(0).Controls.Count > 0 Then
                For Each ctrlControl As Control In gvControl.Rows(intRow).Cells(0).Controls
                    If ctrlControl.GetType.Name <> "LiteralControl" Then
                        If ctrlControl.ID = strControlID Then
                            ctlTarget = ctrlControl
                            Return ctlTarget
                        End If
                    End If
                Next
            End If
        Next

        Return ctlTarget

    End Function
  
0
FuzzieDice
1/30/2007 5:21:29 PM

Is there any point in particular I should call this function from?

 

Regards,

James 

0
jamesmbradley
1/31/2007 3:28:20 PM

Hi, I've just had a quick go and get the following error:

 

Unable to cast object of type 'System.Web.UI.Control' to type 'System.Web.UI.WebControls.TextBox'.

Any ideas?

 

Regards,

 

James 


 

0
jamesmbradley
1/31/2007 3:44:27 PM

Ok, try this code function. Save it to a class file such as LocateControls.vb and include it in your project.

 Public Class LocateControls

    Public Function GVFindControl(ByVal gvControl As GridView, ByVal intRow As Integer, ByVal intColumn As Integer, ByVal strControlID As String) As Control

        Dim ctlTarget As New Control

        For Each dvr As GridViewRow In gvControl.Rows
            If gvControl.Rows(intRow).Cells(intColumn).Controls.Count > 0 Then
                For Each ctrlControl As Control In gvControl.Rows(intRow).Cells(intColumn).Controls
                    If ctrlControl.GetType.Name <> "LiteralControl" Then
                        If ctrlControl.ID = strControlID Then
                            ctlTarget = ctrlControl
                            Return ctlTarget
                        End If
                    End If
                Next
            End If
        Next

        Return ctlTarget

    End Function

  End Class

Now, to call it you first have to define some variables:

Dim lc As New LocateControls

'Let's assume we are looking for a label control
'But it can be anything.
Dim lblMyLabel As New Label

'These are used in my counter loop below
Dim i as Integer
Dim blnFlag as Boolean

Now before you call the function, here are the parameters it will need, in order Left to Right:

1. The ID or Name of the GridView Control. For this example, lets use GridView1.

2. The Row you want to retrieve. Or you can iterate through all rows in a for/next loop as I will in this example.

3. The Column where the control will be found. This is very important. I think this is why the old version of the function was throwing errors sometimes, because it wasn't found. Columns start at 0 on the left.

4. The name of the control you're looking for, enclosed in quotes. Here I'm looking for "lblMyLabel"

So now, let's use some code to find this control. Notice I'm using some exception handling here. This is necessary just in case you can't find the control because there's no other way to tell.

For i = 0 To GridView1.Rows.Count - 1

Try
  'I'm going to assume that the 4th column in the gridview (Column 3)
  'Is where my control is found.
  lblMyLabel = lc.GVFindControl(GridView1, i, 3, "lblMyLabel")
  blnCtlFlag = True
Catch ex As Exception
  'The control wasn't found!
  blnCtlFlag = False
  Exit For
End Try

  If blnCtlFlag = True Then
    lblMyLabel.Text = "This is my control!"
  End If

Next

What is happening here is that it is iterating through all the rows in one particular column to find a control by the name we specify. Then it sets the text to "This is my control!"

If you are very certain that it will always find the control in every row of a column (such as a label to denote yes/no, etc.) then you can probably leave out the exception handling bit. However, if some rows in the column have the control and some don't, you'll need to do exception handling.

I can't figure out any other way for the program to pass information back on whether or not the control was found. It just passes back the control. So you'll have to do some error checking on your own there.


Hope this helps!
 

 

 

0
FuzzieDice
2/1/2007 8:06:38 AM

Hi,

u have provided nice code ...

but after using your code ... still i m not able to locate a listbox lying within EditItemTemplate of a Gridview...

I have following TemplateField of Gridview ...

<

asp:TemplateField>

<ItemTemplate>

<asp:Label ID="lblHost" runat="server" Text='<%# Eval("HostFrom") %>'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:ListBox ID="lstHost" runat="server" SelectionMode="Multiple">

<asp:ListItem Value="TC" Text="Tenders"></asp:ListItem>

<asp:ListItem Value="GT" Text="Global"></asp:ListItem>

<asp:ListItem Value="CC" Text="Projects"></asp:ListItem>

</asp:ListBox>

</EditItemTemplate>

</asp:TemplateField>

 

I am not able to locate the listbox control ... and one more thing I want to know is from which event I should call the function given by you... possible thru RowEditing or something else ... and I am not sure about whether it is possible or not ...

Plz help me to come out the situation ...

Thanks & Regards,

Krupa Parikh

 

0
Krupa
2/12/2007 1:37:48 PM

Ok, I've tried your code and cannot get it to work properly, it will work on the first row in the GridView, but no others! Can you think of any reason why this would be?

 Kind regards,

 James

0
jamesmbradley
2/12/2007 9:08:43 PM

This is weird, because I have no trouble at all performing a FindControl() for an Edit ItemTemplate field on my DetailsView.

 For instance, in my DetailsView1 control I have an "Item Description" field which is a Label in "ReadOnly" mode and an HTMLTextArea in "Edit" and "Insert" modes.

If I want to find the user's input into the TextArea (to perform my update), I call:

    Dim textarea1 As HTMLTextArea = DetailsView1.FindControl("TextArea1")

Then I can do:

  dsDV1.UpdateCommand = "UPDATE [tblItems]  SET  [ItemDescription] = '" & textarea1.Value & "' WHERE [ItemID] = " & selectedItem.ID

 

Is this a fluke, or am I missing something?

 

 

0
Punkcrib
11/7/2007 5:36:55 PM
Reply:

Similar Artilces:

How to access a child control in a templated control?
I am not sure how to access a child control that I addes to a templated control. For example: I drag a Login Control (ID: "Login1") into page in VisualStudio web developer, I can click on it and from the upper right of that control now in my desinger I can choose "convert to template".  Now I can drop in my own control to be added to the Login Control.  Let say I drag over a DropDownList control (ID: "DropDownList1") and place it at the bottom within the Login Control. At run time I might expect to access the my DropDownList control with somethin...

How to access page control (editor control) from user control?
Hi, I want to do something, but I don't know if it's even possible. I'm trying to make a simple application to edit my website. I have a page called editPage.aspx which contains an editor control. (cuteEditor from cutesoft) I also have a Treeview that dynamically populates my website structure. I placed this treeview in a custom control (populateTreeView.ascx) and placed it on the editPage.aspx page. When you click on a html file in the treeview (inside the custom control) I check if the file exists. If it does exists I send it to a class which retrieves the editable region within this ...

Serverside Template Control
I've created a template control what I am running into difficults is during the Page_Load event on my web page I cannot access the child controls in the two possible templates. What I would like to be able to do is set the value or make some changes to the control at runtime but I have not been successful in gaining code access to the control, for example the TEXTBOX1 control in the EditTemplate template.     Does anyone know a good way to preform this task, let alone if I am even using the correct event Example of HTML Render  <aspSample:TextLabe...

Custom Control within a Control Control
I am developing a custom controls that will render headers for different web sites. Within these controls, I want to place another custom control that will change the language. I created the language control and had it implement IPostBackDataHandler. This control works fine if I drag it on a new web form, but if I tell a header custom control to render it problems occur. The Language Selector custom control does not have a Page member anymore and the event handlers do not work. Does anyone have any experience with doing something similiar? Anyone have any suggestions? Thanks, ...

How do I control one control from another control?
I have a page page1.aspx which is within a master page. On page I have a table with two cells. Within each cell I have placed two controls (ascx) that I have developed. Now I'd like to be able to get these two controls to interact. One needs to update the other. One has some search criteria that the other one needs to update its gridview. One needs to make the other visible/not visible at certain times. Out of the box neither control can see each other at all. Is there a good article or someplace I can find some information on how to do this?  AllAboutFocus.com. Information Technolo...

How to access a user control from another user control in a Wizard control
My page has a wizard control and each step is a user control.  I could find the value of a control in step1 user control in the wizard page but not in step2 user control.From wizard.aspx.vb – it worksDim m_title As DropDownList = CType(Me.PersonalBox1.FindControl("ddlTitle1"), DropDownList) Question:How can I find the value of a control(textbox or dropdownlist)in step1 user control from step2 user control? I want to find “PersonalBox1.FindControl("ddlTitle1")” from Step2 AddressBox1. I have tried several ways to access it but no luck. From AddressBox.ascx.vb –...

Access controls in Wizard control header template.
Is this possible?Web dev - spending forever achieving nothing. hi, suppose the control in the header template is a DDL with Id DropDownList1 access it this way DropDownList dp = (DropDownList)Wizard1.FindControl("headerContainer$DropDownList1");        Response.Write(dp.SelectedValue); hope it helpsJessica CaoSincerely,Microsoft Online Community Support“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community ...

Accessing controls inside User control template
Hi, I need to create a user control with one template. That template needs to be like View in MultiView or Wizzard control or Panel. It means, that controls, which are inside should be visible to the page. It will be created just once per control. I need to be able to write :  TextBox1.Text = "Hello world" not : (MyUserControl1.Controls.FindControl("TextBox1") as TextBox).Text = "Hello world" Thanks, radco  If this is a answer to your problem, mark it as answer in right upper corner. It helps other who read your article to known that...

Accessing Child Controls of a Template Server Control
I've created a templated control that has a property called ContentTemplate which is of type ITemplate.  The control works great with the exception of I now have to interact with the child controls via the FindControl method. Markup: <test:MyControl ID="testControl" runat="server"> <ContentTemplate> <asp:Label ID="testLabel" runat="server" /> </ContentTemplate> </test:MyControl>    In order to interact with the child label, testLabel, I now need to do something like this:Dim lbl As La...

A standardized method to access to controls that are within a Templated Control.
Hello, As all of us we know, lots of controls are of the type of "templated controls". This controls can hold, in any of their templated sets other controls. The problem arise when we try to access to the aforementioned controls in the code-behind/beside (I don't know yet how to name this model) file. Could be, in anyway, implemented a standardized way to access to those controls? Apologize my ignorance in this topic. Greetings.VB .Net Coder - Apologize my C# nescienceBest Regards. Hello. What are you trying to do? you can always use FindControl as your last resort, but maybe t...

access user control controls
Hello,  I have a user control and on it button. When I place ascx control on a aspx page, is there a way to access button events in user control. Something like: me.usercontrol1.button.click()   Thanks Here's an example for you: ASPX <%@ page language="C#" masterpagefile="~/MasterPages/Default.master" autoeventwireup="true" codefile="CaptureEventInParent.aspx.cs" inherits="UserControls_CaptureEventInParent" title="UserControls: Capture Event In Parent" %> <%@ register src="Butto...

Access Controls inside Controls
I have a login control (Login1) inside a Login View control (LoginView1). MembershipUser mbr; mbr = Membership.GetUser(Login1.UserName); It can not find control Login1.  Cheers.  MattSystems Engineer / ASP.NET Web Developermbaughan@raecomputing.com You have to use FindControl. Try creating a local Login control using   LoginView1.FindControl("Login1");Remember: mark posts that helped you as the answer to aid future readersWhy UpdatePanels Are DangerousWhy You Should Not Place Your Whole Site In An UpdatePanel MembershipUser mbr; LoginView1.Find...

Access control from another control
Tried to adjust the sample here for my own uses... http://forums.asp.net/779045/ShowPost.aspx But, doesn't want to cooperate. I have a dropdown list on a user control (header.ascx), autopostback = true public string sStyleSheet; private void Page_Load(object sender, System.EventArgs e) { sStyleSheet = "includes/Styles.css"; //Allows the user to change style sheets for the site } public event EventHandler isClicked; private void ddlStyles_SelectedIndexChanged(object sender, System.EventArgs e) { if(ddlStyles.SelectedIndex == 0) sStyleSheet = "Styles.css"; else if(ddlStyles.Sele...

How to access control on user control?
My web form calls a user control with a Link Button. Based on inline condition I have to set visiable =TRUE/FALSE for the Link Button on the user control. Can anybody know how can I do this? Regards,Prakash hi,  u can access control which is in user control using the following,   Dim urCtl As UserControl = LoadControl("urControl.ascx") CType(urCtl , urControl).label1.Visible = True  panel1.Controls.Add(urCtl)     You posted the same question previously and received 2 responses. If these did not solve your problem, could you please post some mor...

Web resources about - How do I access control on edit item template in DataView control? - asp.net.presentation-controls

Template - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Facebook page template & tips for 2014
As Facebook page admins get started with 2014, the social marketing experts at ShortStack created a detailed template , including image sizes, ...

Frame Artist Pro - Best Photo Collage Editor, Stitch Your Photos with Pic Frame Templates & Filter Effect ...
Get Frame Artist Pro - Best Photo Collage Editor, Stitch Your Photos with Pic Frame Templates & Filter Effect & Frames on the App Store. See ...

Paper wireframe templates - Flickr - Photo Sharing!
jasonrobb.com/v2/i/Wireframe-templates-JasonRobb.zip jasonrobb.com

United Airlines accidentally sends letter template to unhappy passenger
A US air passenger may have received what is quite possibly the world’s least sincere apology letter.

TV Templates - Transcripts
Lorem ipsum dolor sit amet, aihiad adaph dpas, osaf das. Oi asdfpo ijafj ai.

Mockup Apple Watch apps and compare screen sizes with these official bezel templates
... for developers, readers interested in Apple Watch can also use the images to compare the overall physical size of the two sizes. The templates ...

Today’s apps gone free: Practice+, Templates for Keynote, Dr. Panda’s Mailman and more
... and packages. Dr. Panda’s Postman is available for free for a limited time. It has a 4.5-star rating with a total of 44 ratings. Templates ...

Templates, Insights and Dictation in Google Docs
Google's standalone web apps for Docs , Sheets and Slides now show a list of templates you can choose to quickly create a document, spreadsheet ...

Yellen May Emulate Taper Template and Raise Rates in December
TIME Yellen May Emulate Taper Template and Raise Rates in December Bloomberg Federal Reserve Chair Janet Yellen shows signs of taking a page ...

Resources last updated: 11/29/2015 2:54:25 PM