0

我有 3 个文本框来添加技能,它们进入一个名为“SkillName”的列。但是,我收到了这个错误。

'System.Web.UI.Control' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?)

但是我使用了 System.Web.UI.WebControls 的程序集;

这是我添加文本框的代码-

 public void InsertSkillInfo()
        {


            String str = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=DBNAME;Integrated Security=True";
            SqlConnection conn = new SqlConnection(str);

            try
            {

                for (int i = 1; i <= 3; i++)
                {
                    conn.Open();
                    **string skill = (Page.FindControl("TextBox" + i.ToString())).Text;**
                    const string sqlStatement = "INSERT INTO Cert (SkillName) VALUES (@SkillName)";
                    SqlCommand cmd = new SqlCommand(sqlStatement, conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters["@SkillName"].Value = skill;
                    cmd.ExecuteNonQuery();
                }
            }

            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Insert Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }

            finally
            {
                conn.Close();
            }

         } 
4

3 回答 3

2

Page.FindControl将返回一个Control,但你想要一个文本框。如果您确定它找到的控件始终是文本框,则将其转换为文本框。

任何一个:

string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;

或者

var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if(control != null {
    skill = control.Text;
}
于 2012-07-26T09:31:09.380 回答
0

您需要将控件强制转换为 TexBox 所以它应该是这个

string skill = ((TextBox) Page.FindControl("TextBox" + i.ToString())).Text;
于 2012-07-26T09:30:14.410 回答
0

您可以像这样简单地尝试

string skill = ((TextBox)(Page.FindControl("TextBox" + i.ToString()))).Text;
于 2012-07-26T09:30:25.550 回答