Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

asp.net - Unable to cast object of type ‘System.Web.UI.LiteralControl’ Error

I am getting this error: Unable to cast object of type ‘System.Web.UI.LiteralControl’ to type ‘System.Web.Controls.TextBox’

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;

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;

Please note if I remove the querystring from the ASPX page and then I insert the value manually then it works. Pls. help. thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is here:

(TextBox)GV_InlineEditing.Rows[0].Cells[2].Controls[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;

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?
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...