无法投类型的对象'System.Web.UI.LiteralControl“错误 [英] Unable to cast object of type ‘System.Web.UI.LiteralControl’ Error
问题描述
我得到这个错误:
无法投类型的对象System.Web.UI.LiteralControl为键入'System.Web.Controls.TextBox
I am getting this error: Unable to cast object of type ‘System.Web.UI.LiteralControl’ to type ‘System.Web.Controls.TextBox’
我从ASPX页面查询字符串喂我的文本输入框,这里是code:
I am feeding my Text input box from a querystring in the ASPX page and here is the code:
<EditItemTemplate>
<asp:TextBox ID="GV_Post_ID" runat="server" text='<%# Request.QueryString["Post_ID"] %>'></asp:TextBox>
</EditItemTemplate>
但是当我运行它,它止于此:
But when I run it, it stops here:
cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = ((TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[0]).Text;
和我得到上述错误。这里是code背后:
and I get the error above. Here is the code behind:
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;
请注意,如果我从ASPX页面中删除查询字符串,然后我将值手动,然后它的作品。 PLS。帮帮我。
谢谢
Please note if I remove the querystring from the ASPX page and then I insert the value manually then it works. Pls. help. thanks
推荐答案
该问题是在这里:
(文本框)GV_InlineEditing.Rows [0] .Cells [2] .Controls [0]
在单元格中的第一个控制不是文本框
你认为它是。让我们假设 GV_InlineEditing.Rows [0]
被安全地得到你所需要的行。做这样的事情:
The first control in that cell isn't the TextBox
you think it is. Let's assume GV_InlineEditing.Rows[0]
is safely getting you the row you need. Do something like this:
TextBox myTextBox = GV_InlineEditing.Rows[0].FindControl("GV_Post_ID") as TextBox;
cmd.Parameters.Add("@Post_ID", SqlDbType.VarChar).Value = myTextBox.Text;
这code可以更加安全的是这样的:
That code can be even more safe like this:
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?
}
这篇关于无法投类型的对象'System.Web.UI.LiteralControl“错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!