Problem with ListView.EditItem.FindControl

TikkTakk-Aicon
TikkTakk-Aicon used Ask the Experts™
on
I´m scratching my head over an error I get only when I have posted my site to the server (no error occurs when I run my project locally).

Inside a ListView I have a DropDownList that updates two textboxes when changed (user selects a number from the ddl and two textboxes text changes to the corresponding number).  The ddl uses SQLDataSource to retrieve the information from the database.

I get this error when selecting something from the ddl:  Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 107:        tbFlokkur = Me.ListView2.EditItem.FindControl("FlokkurEditTextBox")

I have two functions in the codebehind, one for the selectindexchanged on the ddl and one for the ItemUpdateing for the Listview.  In both these functions I need to access the textboxes and other controls in the EditItemTemplate.  I have tried several ways for this, i.e. DirectCast(ListView2.EditItem.FindControl("FlokkurEditTextBox"), TextBox) and other things without any luck.  Below is my code for those two functions
Protected Sub ddlNumer2_SelectIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim numer As Integer
        Dim sqry, strengur1, strengur2 As String
        Dim Months As New Double
        Dim SecondDate As New Date
        Dim IntervalType As New DateInterval
        Dim tbFlokkur, tbAtridi, tbFrestur, tbELSnumer As TextBox

        IntervalType = DateInterval.Month

        'Here is something I have been trying
        'tbFlokkur1 = DirectCast(ListView2.EditItem.FindControl("FlokkurEditTextBox"), TextBox)

        'Here below is my original code
        tbFlokkur = Me.ListView2.EditItem.FindControl("FlokkurEditTextBox")
        tbAtridi = Me.ListView2.EditItem.FindControl("AtriðiEditTextBox")
        tbFrestur = Me.ListView2.EditItem.FindControl("Frestur_til_endurbótaEditTextBox")
        tbELSnumer = Me.ListView2.EditItem.FindControl("ELS_númerEditTextBox")

        numer = sender.SelectedValue

        sqry = "SELECT [Atriði], [Flokkur] FROM [taf_eftirlit_skodunaratridi] where [Númer] =" & numer & ""
        da = New SqlDataAdapter(sqry, getConnectionString())
        da.Fill(ds)

        strengur1 = ds.Tables(0).Rows(0).Item(0)
        strengur2 = ds.Tables(0).Rows(0).Item(1)

        If ds.Tables(0).Rows.Item(0) Is Nothing Then
            Response.Write("Villa")
        Else
            tbELSnumer.Text = Request.QueryString("ELSnumer")
            tbFlokkur.Text = strengur1
            tbAtridi.Text = strengur2
            tbFrestur.Text = DateAdd(IntervalType, 12, Date.Today)
        End If

    End Sub

Protected Sub ListView2_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles ListView2.ItemUpdating
        e.OldValues.Clear()
        e.NewValues.Clear()


        Dim ELS_númerEditTextBox As New TextBox
        Dim ddlNumer2 As New DropDownList
        Dim FravikSelect As New System.Web.UI.HtmlControls.HtmlSelect
        Dim AthugasemdTextBox As New TextBox
        Dim Frestur_til_endurbótaTextBox As New TextBox
        Dim fravik, alvarlegtfravik, athugasemd As String

        fravik = "Frávik"
        alvarlegtfravik = "Alvarlegt frávik"
        athugasemd = "Athugasemd"

        ELS_númerEditTextBox = ListView2.EditItem.FindControl("ELS_númerEditTextBox")
        ddlNumer2 = ListView2.EditItem.FindControl("ddlNumer2")
        FravikSelect = ListView2.EditItem.FindControl("FravikSelect")
        AthugasemdTextBox = ListView2.EditItem.FindControl("AthugasemdTextBox")
        Frestur_til_endurbótaTextBox = ListView2.EditItem.FindControl("Frestur_til_endurbótaEditTextBox")


        e.NewValues("ELS_numer") = Request.QueryString("ELSnumer")
        e.NewValues("Numer") = ddlNumer2.SelectedValue
        e.NewValues("Athugasemd") = AthugasemdTextBox.Text
        If FravikSelect.SelectedIndex = 0 Then
            e.NewValues("Fravik") = athugasemd
        ElseIf FravikSelect.SelectedIndex = 1 Then
            e.NewValues("Fravik") = fravik
        Else
            e.NewValues("Fravik") = alvarlegtfravik
        End If
        e.NewValues("Frestur_til_endurbota") = Frestur_til_endurbótaTextBox.Text
    End Sub

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Obadiah ChristopherDeveloper User Interface

Commented:
Just place a breakpoint in the line u mentioned as giving error

and check this in immediate window

ListView2.EditItem.Controls.Count.

I think u may have to do something like this

ListViewRow lvRow =((DropdownList)sender).NamingContainer

lvRow.FindControl("txtBoxID")

Author

Commented:
When I put this, Response.write(ListView2.EditItem.Controls.Count.) into my ddlNumer2_SelectIndexChanged function I get the number 3, the same goes for this in the other function, the number of controls are 3.

I can´t declare something called ListViewRow...
Most Valuable Expert 2012
Top Expert 2014

Commented:
See the example in this link about how to access new values
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewupdateeventargs.aspx

Also try this
Dim lItem as ListViewItem = CType(Sender, DropDownList).NamingContainer
ddlNumer2 = lItem.FindControl("ddlNumer2")
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
It´s not only the ddlNumer2 I´m having trouble finding all the controls in the edititemtemplate in this listview.  Can I use CType for the textboxes also ?
Most Valuable Expert 2012
Top Expert 2014

Commented:
Yes. But atleast you can give it a try to find one control and if it works then you can use it for all controls.

Author

Commented:
Well I have two functions for this listview when updating.  If the DropDownList value is changed I need to fill two textboxes with strings that correspond to the selectedvalue.  Then in the ListiView_ItemUpdating function I need to get the values from all the controls to insert into the database (I use a stored proc to update the table in SQL)

When I try to have only the code you supplied in the ItemUpdating function I get this error

Unable to cast object of type 'System.Web.UI.WebControls.ListView' to type 'System.Web.UI.WebControls.DropDownList'.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Hmmm. Try changing this
Dim lItem as ListViewItem = CType(Sender, DropDownList).NamingContainer

to
Dim lItem as ListViewItem = CType(Sender, ListViewItem).NamingContainer

You may have to tweak it a bit to suit your needs.

Author

Commented:
Then I get this error, Unable to cast object of type 'System.Web.UI.WebControls.ListView' to type 'System.Web.UI.WebControls.ListViewItem'.

and when I try to have this instead, Dim lItem as ListViewItem = CType(Sender, ListView).NamingContainer I get another error...
Most Valuable Expert 2012
Top Expert 2014

Commented:
Ok. Try this then

Dim lItem as ListView = CType(Sender, ListView).NamingContainer

Author

Commented:
Then this error comes up

Unable to cast object of type 'ASP.eftirlit_aspx' to type 'System.Web.UI.WebControls.ListView'.

Author

Commented:
And when I put this line in the selectedindexchanged function I get this error

Unable to cast object of type 'System.Web.UI.WebControls.DropDownList' to type 'System.Web.UI.WebControls.ListView'.

Author

Commented:
I received an email with a new comment added... but I see no new comment on this...
Most Valuable Expert 2012
Top Expert 2014

Commented:
>Unable to cast object of type 'System.Web.UI.WebControls.DropDownList' to type 'System.Web.UI.WebControls.ListView'.

Obviously the above error is quite self explainatory. Try

Dim tList as DropDownList = CType(Sender, DropDownList).NamingContainer

if you are using it inside the selectedindexchangeg event of a dropdownlist.

Author

Commented:
I think we are not on the same page here.  In the selectedindexchanged event of the dropdownlist I don´t need to access the dropdownlist, just two other textboxes.  But in the ItemUpdating event I have to access all the controls, including the dropdownlist to insert the new values into the database.
Most Valuable Expert 2012
Top Expert 2014
Commented:
We are trying to get to the parent container of the DDL mate so that we can then use that to get access to its fellow controls. Is the DDL hosted in the EditTemplate of the ListView? Try this line

Dim lView As ListView = CType(Sender, DropDownList).NamingContainer

Then we can use

Dim txt As TextBox = lView.FindControl ("textboxname")

Author

Commented:
Ok, I got an error on that and changed ListView to ListViewDataItem, like this

Dim lView As ListViewDataItem = CType(sender, DropDownList).NamingContainer

YESYESYES then I tried to do this for the controls:

 tbFlokkur = lView.FindControl("FlokkurEditTextBox")
tbAtridi = lView.FindControl("AtriðiEditTextBox")
tbFrestur = lView.FindControl("Frestur_til_endurbótaEditTextBox")
tbELSnumer = lView.FindControl("ELS_númerEditTextBox")

And I get no error when I change the number in the dropdownlist and the textboxes get new values.  Thank you so much !!

Now there is the second half of this problem... This line, Dim lView As ListView = CType(sender, ListView).NamingContainer does not work in the ItemUpdating event on the listview.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Try
Dim LV as ListView = Ctype(Sender, ListView)

Author

Commented:
It seems to work but I get an Object reference not set to an instance of an object error on this line e.NewValues("Numer") = ddlNumer2.SelectedValue
Most Valuable Expert 2012
Top Expert 2014

Commented:
Its probably because the FindControl did not find any control and ddlNumer2 is nothing. Try adding a IsNothing check to confirm this.

Author

Commented:
Yes, I added this around
If ddlNumer2 Is Nothing Then
            Response.Write("Error")
        Else
            e.NewValues("Numer") = ddlNumer2.SelectedValue
        End If

and it skips to the next line which generates an error (because I didn´t add a IsNothing check there)
Most Valuable Expert 2012
Top Expert 2014

Commented:
Comment out rest of the controls for the time being and see if you get the "Error" in browser.

Author

Commented:
That was strange... when I press the Update button this specific item in the listview disappears....
Most Valuable Expert 2012
Top Expert 2014

Commented:
hmm. May be at this stage, the template of the ListView is changed from Edit to normal. Also, if you are setting the e.NewValues = controls from the edit template, what's the difference? Are the newvalues not taken from those controls?

Author

Commented:
Well I was having trouble with updating the ListView so I found a way to make it work like this... I tried now to comment out the whole ItemUpdated event and when I press the button the information in the listview is not updated....
Most Valuable Expert 2012
Top Expert 2014

Commented:
Is it bound to a SQLDataSource?

Author

Commented:
In the ItemUpdated event on the ListView I redirect to the same page with the right querystrings...
Most Valuable Expert 2012
Top Expert 2014

Commented:
I did not understand. Is the listview bound to a properly configured datasource?

Show me the code in ItemUpdated.

Author

Commented:
This was working before... I guess I need to fix this and rebdind the listview to the newly updated data.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Both of my questions are still not answered.

Author

Commented:
Yes, the ListView is bound to a properly figured SQLDataSource.  I have no code in the ItemUpdated or ItemUpdating events now, I am simply trying to use the UpdateParameters and the UpdatecommandType is a stored procedure.  Below is my datasource and the edititemtemplate in the listview.  When I update, the table in the database has all values as NULL ....

Author

Commented:
Sorry, it didn´t attach....
<EditItemTemplate>
                <td runat="server" style="width: 820px;">                    
                    Færslunúmer:
                    <asp:TextBox ID="FaerslunumerEditTextBox" runat="server" Text='<%# Eval("Faerslunumer") %>' Enabled="false" />
                    <br />
                    ELS-númer:
                    <asp:TextBox ID="ELS_númerEditTextBox" runat="server" Text='<%# Eval("[ELS-númer]") %>' Enabled="false" />
                    <br />
                    Númer:
                    <asp:DropDownList ID="ddlNumer2" runat="server" AppendDataBoundItems="true" AutoPostBack="True" SelectedValue='<%# Eval("Númer") %>' 
                         DataSourceID="dsNumer" DataTextField="Númer" DataValueField="Númer" OnSelectedIndexChanged="ddlNumer2_SelectIndexChanged" />
                    <br />
                    Flokkur:
                    <asp:TextBox ID="FlokkurEditTextBox" runat="server" Text='<%# Eval("Flokkur") %>' />
                    <br />
                    Atriði:
                    <asp:TextBox ID="AtriðiEditTextBox" runat="server" Text='<%# Eval("Atriði") %>' />
                    <br />
                    Fravik:
                    <select id="FravikSelect" runat="server">
                            <option value="Athugasemd">Athugasemd</option>
                            <option value="Fravik" selected="selected">Frávik</option>
                            <option value="Alvarlegt Fravik">Alvarlegt frávik</option>                            
                        </select>
                    <br />
                    Athugasemd:
                    <asp:TextBox ID="AthugasemdTextBox" runat="server" TextMode="MultiLine"
                        Text='<%# Eval("Athugasemd") %>' />
                    <br />
                    Frestur til endurbóta:
                    <asp:TextBox ID="Frestur_til_endurbótaEditTextBox" runat="server" 
                        Text='<%# Eval("[Frestur til endurbóta]", "{0:dd.MM.yyyy}") %>' />
                    <br />
                    <asp:Button ID="UpdateButton" runat="server" CommandName="Update" 
                        Text="Breyta" />
                    <br />
                    <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" 
                        Text="Hætta við" />
                    <br />
                </td>
            </EditItemTemplate>

<asp:SqlDataSource ID="dsEftirlitListView" runat="server" 
            ConnectionString="<%$ ConnectionStrings:MAST_eftirlitConnectionString %>" 
            InsertCommand="NyttAthugasemdaeftirlit" 
            InsertCommandType="StoredProcedure" 
            UpdateCommand="UppfaeraAthugasemdaEftirlit" UpdateCommandType="StoredProcedure"            
            SelectCommand="SELECT taf_eftirlit_Athugasemdir.Faerslunumer, taf_eftirlit_Athugasemdir.[ELS-númer], taf_eftirlit_skodunaratridi.Númer, taf_eftirlit_skodunaratridi.Flokkur, 
	                taf_eftirlit_skodunaratridi.Atriði, taf_eftirlit_Athugasemdir.Fravik, taf_eftirlit_Athugasemdir.Vegna, 
	                taf_eftirlit_Athugasemdir.Athugasemd, taf_eftirlit_Athugasemdir.[Frestur til endurbóta]
                FROM Fyrirtækjaeftirlit INNER JOIN taf_eftirlit_Athugasemdir ON Fyrirtækjaeftirlit.[ELS-númer] = taf_eftirlit_athugasemdir.[ELS-númer] INNER JOIN
	                taf_eftirlit_skodunaratridi ON taf_eftirlit_Athugasemdir.Númer = taf_eftirlit_skodunaratridi.Númer INNER JOIN
	                Eftirlit ON Fyrirtækjaeftirlit.[EL-kenni] = Eftirlit.[EL-kenni]
                WHERE Fyrirtækjaeftirlit.Busnumer = @Busnumer and taf_eftirlit_athugasemdir.[ELS-númer] = @ELSnumer">
            <SelectParameters>
                <asp:QueryStringParameter Name="Busnumer" QueryStringField="Busnumer" />
                <asp:QueryStringParameter Name="ELSnumer" QueryStringField="ELSnumer" />
            </SelectParameters>
            <UpdateParameters>
                <asp:Parameter Name="Faerslunumer" Type="Int32" />
                <asp:Parameter Name="ELS_numer" Type="Int32" />
                <asp:Parameter Name="Numer" Type="Int32" />
                <asp:Parameter Name="Athugasemd" Type="String" />
                <asp:Parameter Name="Fravik" Type="String" />
                <asp:Parameter Name="Frestur_til_endurbota" Type="DateTime" />                
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="ELS_numer" Type="Int32" />
                <asp:Parameter Name="Numer" Type="Int32" />
                <asp:Parameter Name="Athugasemd" Type="String" />
                <asp:Parameter Name="Fravik" Type="String" />
                <asp:Parameter Name="Frestur_til_endurbota" Type="DateTime" />
            </InsertParameters>
        </asp:SqlDataSource>

Open in new window

Most Valuable Expert 2012
Top Expert 2014

Commented:
I am in bed now so would respond 2maro morning.
Most Valuable Expert 2012
Top Expert 2014

Commented:
You need to use the ControlParameter instead of asp:Parameter. Check the example here

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.updateparameters.aspx

Author

Commented:
Then I´m right back at the reason I used this ItemUpdating event in the codeehind.  I get this error when updating: Could not find control 'ListView1$FaerslunumerEditTextBox' in ControlParameter 'Faerslunumer'.

Below are the parameters.
<UpdateParameters>
                <asp:ControlParameter Name="Faerslunumer" ControlID="ListView1$FaerslunumerEditTextBox" PropertyName="Text" />
                <asp:ControlParameter Name="ELS_numer" ControlID="ListView1$ELS_númerEditTextBox" PropertyName="Text" />
                <asp:ControlParameter Name="Numer" ControlID="ListView1$ddlNumer2" PropertyName="SelectedValue" />
                <asp:ControlParameter Name="Athugasemd" ControlID="ListView1$AthugasemdTextBox" PropertyName="Text" />
                <asp:ControlParameter Name="Fravik" ControlID="ListView1$FravikSelect" PropertyName="SelectedValue" />
                <asp:ControlParameter Name="Frestur_til_endurbota" ControlID="ListView1$Frestur_til_endurbótaEditTextBox" PropertyName="Text" />                
            </UpdateParameters>

Open in new window

Author

Commented:
Sorry, a little copy/paste error from me, ListView1 should be ListView2 because that is the ID of the ListView
Most Valuable Expert 2012
Top Expert 2014

Commented:
Use the name of the textbox instead of this
ListView1$FaerslunumerEditTextBox

Just use  FaerslunumerEditTextBox

Author

Commented:
I tried that at first and got the same error
Most Valuable Expert 2012
Top Expert 2014

Commented:

Author

Commented:
This example is using objectdatasource, I´m not familiar with that.
Most Valuable Expert 2012
Top Expert 2014

Commented:
Its the overall concept rather than the specific type of control used which you need to understand.

Author

Commented:
Well, call me stupid... I don´t know how the hell I can edit my code by looking at this
Most Valuable Expert 2012
Top Expert 2014

Commented:
Do you call the SQLDataSource1.Update anywhere bytheway?

Author

Commented:
No

Author

Commented:
I´m not getting an error on the first update parameter

<asp:ControlParameter Name="Faerslunumer" ControlID="ListView2" PropertyName="SelectedValue" />
                <asp:ControlParameter Name="ELS-númer" ControlID="ELS_númerEditTextBox" PropertyName="Text" />

Am I right when I say that the name should be the same as the field name in the database table, or should the name be the same as the parameter in the stored procedure ?
Most Valuable Expert 2012
Top Expert 2014

Commented:
That is the method which would update the database by the way. Can you show me a screenshot of your page?
Most Valuable Expert 2012
Top Expert 2014

Commented:
It should match with the SP parameter name.
Most Valuable Expert 2012
Top Expert 2014

Commented:
What error do you get?

Author

Commented:
Could not find control 'ELS_numerEditTextBox' in ControlParameter 'ELS_numer'.
Most Valuable Expert 2012
Top Expert 2014

Commented:
I give up mate. Its easier to do when the controls are on the main form rather than in the edit template of a listview.

Author

Commented:
Here is the screenshot of my page
screenshot.jpg

Author

Commented:
Then I must try to do this in the codebeheind, but then I can´t access the controls to get the values... this is really annoying, do you recommend some other control for this ?  I need to list all the comments made on this specific surveillance, they should be editable and users should be able to insert new comments
Most Valuable Expert 2012
Top Expert 2014

Commented:
How about using a datagridview or a datalist?

Author

Commented:
Datalist seems to be good, but can I insert through that ?  It doesn´t seem to support InsertItemTemplate
Most Valuable Expert 2012
Top Expert 2014

Commented:

Author

Commented:
I found another way for this, http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/Q_20794863.html

I have successfully managed to insert new comments and now I´m going to start working on the editing inside the datalist (hopefully I can manage that without big problems).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial