我收到此错误:
无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为“System.Web.Controls.TextBox”类型
无法将类型为“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>
但是当我运行它时,它停在这里:
cmd.Parameters.Add("@Post_ID",sqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0]).Text;
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;
解决方法
问题出在这里:
(文本框)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;
该代码可以更加安全,如下所示:
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? }