无法转换'System.Web.UI.LiteralControl'类型的对象错误

moe*_*moe 6 asp.net asp.net-mvc

我收到此错误:无法将"System.Web.UI.LiteralControl"类型的对象强制转换为"System.Web.Controls.TextBox"类型

我从ASPX页面的查询字符串中输入我的文本输入框,这里是代码:

<EditItemTemplate>
                        <asp:TextBox ID="GV_Post_ID" runat="server" text='<%# Request.QueryString["Post_ID"] %>'></asp:TextBox>
                    </EditItemTemplate>
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它停在这里:

cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0]).Text;
Run Code Online (Sandbox Code Playgroud)

我得到上面的错误.这是后面的代码:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DSRConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO RCA_Events(Post_ID, Date, Description) VALUES(@Post_ID, @Date, @Description)";
            cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0]).Text;
            cmd.Parameters.Add("@Date", SqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[3].Controls[0]).Text;
            cmd.Parameters.Add("@Description", SqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[4].Controls[0]).Text;
Run Code Online (Sandbox Code Playgroud)

请注意,如果我从ASPX页面中删除查询字符串,然后我手动插入值,那么它的工作原理.PLS.救命.谢谢

Gro*_*mer 9

问题出在这里:

(TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0]

该单元格中的第一个控件不是TextBox您认为的那样.让我们假设GV_InlineEditing.Rows[0]安全地为您提供所需的行.做这样的事情:

TextBox myTextBox = GV_InlineEditing.Rows[0].FindControl("GV_Post_ID") as TextBox;
cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = myTextBox.Text;
Run Code Online (Sandbox Code Playgroud)

该代码可以更加安全,如下所示:

TextBox myTextBox = GV_InlineEditing.Rows[0].FindControl("GV_Post_ID") as TextBox;
if (myTextBox != null)
{
    cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = myTextBox.Text;
}
else
{
    // Do something here.  Default value for the post id?
}
Run Code Online (Sandbox Code Playgroud)


Elk*_*ver 5

问题是当您使用 Gridviews 并将Databound字段转换为ItemTemplates时,例如将一个文本框添加到 EditItemTemplate 中然后将其自己的 ID 添加到该文本框(例如 txtProduct)中,函数.controls[0]将不会如果找不到它,它不知道您的文本框的 ID,因此在这种情况下,您必须提供要定位的文本框的 ID。因此,您应该使用.FindControl("txtProduct")而不是使用.Controls[0]。在你的情况下而不是:

(TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0].Text;
Run Code Online (Sandbox Code Playgroud)

你应该做这个:

(TextBox)GV_InlineEditing.Rows[0].Cells[2].FindControl("GV_Post_ID").Text;
Run Code Online (Sandbox Code Playgroud)