简体   繁体   English

如何解决“无法将类型'ASP.addtoroster_aspx'的对象强制转换为'System.Web.UI.WebControls.GridViewRow'错误?

[英]How do I resolve "Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow' error?

We have a dropdownlist in gridview that gets populated from the database. 我们在gridview中有一个下拉列表,它从数据库中填充。

There is a also a textbox next to this dropdownlist. 此下拉列表旁边还有一个文本框。

If the option the user is looking for isn't in the dropdown, enter that value into the textbox and when submitted to the database, will now become in the dropdownlist. 如果用户正在查找的选项不在下拉列表中,请将该值输入文本框,并在提交到数据库时,现在将进入下拉列表。

I am running into the following error: 我遇到以下错误:

Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow'.

The error is on this line: 错误在这一行:

Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow ) Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow

I believe this error occurs because I am using an imagebutton on the markup to submit to the database. 我相信发生此错误是因为我在标记上使用图像按钮提交到数据库。

<asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/save.png" 
                                             onmouseout="this.src='images/save.png'" 
                                             onmouseover="this.src='images/save.png'"

 OnClick="btnSave_Click" alt="Save Data" /> 

Any idea how to resolve this? 知道如何解决这个问题吗?

Even though this is vb, I welcome solution in c# if available. 即使这是vb,我也欢迎使用c#中的解决方案。

Thank you! 谢谢!

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
    ' Try
    SetRowData()
    Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)

    If table IsNot Nothing Then
        For Each row As DataRow In table.Rows
            Dim txLName As String = TryCast(row.ItemArray(1), String)
            Dim txName As String = TryCast(row.ItemArray(2), String)
            Dim txEmail As String = TryCast(row.ItemArray(3), String)
            Dim txRole As String = TryCast(row.ItemArray(4), String)
            Dim txPhone As String = TryCast(row.ItemArray(5), String)
            Dim drpEmpl As String = TryCast(row.ItemArray(6), String)
            Dim txVIP As String = TryCast(row.ItemArray(7), String)
            Dim drpLCB As String = TryCast(row.ItemArray(8), String)

            'Find the button
            Dim button As Button = DirectCast(sender, Button)
            'Find parent row
            Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
            'find DropDownlist and textbox
            Dim ddl As DropDownList = TryCast(parentRow.FindControl("txtLoginName"), DropDownList)
            Dim txtNewUser As TextBox = TryCast(parentRow.FindControl("txtNewUser"), TextBox)
            If txtNewUser IsNot Nothing AndAlso ddl IsNot Nothing Then
                'add new listitem here
                Dim customItem As New ListItem(txtNewUser.Text, txtNewUser.Text)
                ddl.Items.Add(customItem)
            End If

            Dim ddlvalue As String = ""
            Dim idx As Integer = grvStudentDetails.EditIndex

            If drpEmpl = "Other" Then
                ddlvalue = DirectCast(grvStudentDetails.FindControl("txtOther"), TextBox).Text

                '   Else
                '      ddlvalue = drpEmpl
            End If


            If txLName IsNot Nothing OrElse txLName IsNot Nothing OrElse txEmail IsNot Nothing OrElse txRole IsNot Nothing OrElse txPhone IsNot Nothing OrElse drpEmpl IsNot Nothing OrElse txVIP IsNot Nothing OrElse drpLCB IsNot Nothing Then
                ' Response.Write(String.Format("{0} {1} {2} {3} {4} {5} {6} {7} <br/>", txLName, txName, txEmail, txRole, txPhone, drpEmpl, txVIP, drpLCB))

                'Try
                Dim dateentered As String = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
                'Response.Write(dateentered)
                'Response.End()

                Dim s As String
                Dim count As Integer

                'If LoginName already exists, alert user
                s = "SELECT Count(*) FROM Employee_Roster WHERE login_id = " & txLName
                'Response.Write(s)
                'Response.End()
                Dim connSt As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
                Dim connc As New OleDbConnection(connSt)
                Dim cmdc As New OleDbCommand(s, connc)
                'cmdc.Parameters.AddWithValue("login_id", txtLoginName.SelectedValue)
                connc.Open()
                ' cmdc.ExecuteNonQuery()
                count = cmdc.ExecuteScalar()


                '   Now let's see if we found existing record
                If count > 0 Then
                    'Display some feedback to the user to let them know it was processed
                    lblResult.ForeColor = System.Drawing.Color.Green
                    lblResult.Text = "User already is in the Excel Sheet!"
                Else
                    s = "INSERT INTO Employee_Roster(login_id, FullName, Email_Address, Role_Dept,Phone,Employer,VP,entryDate,Notes) VALUES "
                    s += "('" & txLName & "', '" & txName & "', '" & txEmail & "', '" & txRole & "', '" & txPhone & "', '" & ddlvalue & "','" & txVIP & "','" & dateentered & "', '" & drpLCB & "')"
                    Response.Write(s)
                    Response.End()
                    Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
                    Dim conn As New OleDbConnection(connStr)
                    Dim cmd As New OleDbCommand(s, conn)
                    conn.Open()
                    cmd.ExecuteNonQuery()
                    conn.Close()


                    'Display some feedback to the user to let them know it was processed
                    lblResult.ForeColor = System.Drawing.Color.Green
                    lblResult.Text = "Record successfully saved!"

                    'Clear the form
                    txLName = ""
                    txLName = ""
                    txEmail = ""
                    txRole = ""
                    txPhone = ""
                    txVIP = ""
                End If
                ' Catch

                'If the message failed at some point, let the user know
                lblResult.ForeColor = System.Drawing.Color.Red
                lblResult.Text = "Your record failed to save, please try again."

                ' End Try

            End If
        Next
    End If
    '  Catch ex As Exception
    'Throw New Exception(ex.Message)
    ' End Try
End Sub

Its very clear that your controls are residing inside your page and casting button.NamingContainer to GridViewRow is invalid. 很明显,你的控件都驻留在你的页面内并且转换了button.NamingContainerGridViewRow是无效的。

The solution is that you don't need to use the FindControl if your controls have this property set runat="server" . 解决方案是,如果控件具有此属性设置为runat="server"则不需要使用FindControl Just use the ID you give to them. 只需使用您提供给他们的ID即可。

One more thing to point out is you need to use parametrized queries. 还有一点需要指出的是,您需要使用参数化查询。 Your queries are prone to SQL Injection . 您的查询很容易出现SQL注入 check How do I create a parameterized SQL query? 检查如何创建参数化SQL查询? Why Should I? 我为什么要?

Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)

this button is out side of Gridview and this button belongs to ASP.addtoroster_aspx 此按钮位于Gridview外侧,此按钮属于ASP.addtoroster_aspx

but when you say button.NamingContainer it points ASP.addtoroster_aspx as it holds that 但是当你说button.NamingContainer它指向ASP.addtoroster_aspx ,因为它认为,

button,so casting is failing. 按钮,所以铸造失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将类型为“ System.String”的对象转换为类型为“ System.Web.UI.WebControls.GridViewRow” - Unable to cast object of type 'System.String' to type 'System.Web.UI.WebControls.GridViewRow' 无法将类型为“ Obout.Grid.GridTemplate”的对象转换为类型为“ System.Web.UI.WebControls.GridViewRow”的对象。 不解决 - Unable to cast object of type 'Obout.Grid.GridTemplate' to type 'System.Web.UI.WebControls.GridViewRow'. not resolving 无法将类型为“ System.Web.UI.WebControls.ContentPlaceHolder”的对象转换为类型为“ System.Web.UI.WebControls.GridViewRow”的对象 - Unable to cast object of type 'System.Web.UI.WebControls.ContentPlaceHolder' to type 'System.Web.UI.WebControls.GridViewRow' 无法将类型为“ System.Web.UI.HtmlControls.HtmlForm”的对象转换为类型为“ System.Web.UI.WebControls.GridViewRow”的对象 - Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlForm' to type 'System.Web.UI.WebControls.GridViewRow' 从对象类型System.Web.UI.WebControls.GridViewRow到已知托管提供程序本机类型的映射不存在 - No mapping exists from object type System.Web.UI.WebControls.GridViewRow to a known managed provider native type 无法将类型为“ ASP.webform1_aspx”的对象转换为类型为“ System.Web.UI.WebControls.Button”的对象 - Unable to cast object of type 'ASP.webform1_aspx' to type 'System.Web.UI.WebControls.Button' 无法将类型为“ ASP.Catalogue_aspx”的对象转换为类型为“ System.Web.UI.WebControls.LinkBut​​ton”的对象 - Unable to cast object of type 'ASP.Catalogue_aspx' to type 'System.Web.UI.WebControls.LinkButton' System.Web.UI.WebControls.GridViewRow&#39;在此上下文中不可访问,因为它是&#39;Friend&#39; - System.Web.UI.WebControls.GridViewRow' is not accessible in this context because it is 'Friend' 无法在ASP.NET中强制转换System.Web.UI.WebControls.GridView类型的对象 - Unable to cast object of type System.Web.UI.WebControls.GridView in ASP.NET 无法将类型为“ System.Web.UI.LiteralControl”的对象转换为类型为“ System.Web.UI.WebControls.RequiredFieldValidator”的对象。 - Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.RequiredFieldValidator'.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM