我有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();
}
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您需要将控件转换为文本框,因此它应该是
string skill = ((TextBox) Page.FindControl("TextBox" + i.ToString())).Text;
答案 2 :(得分:0)
您可以像这样尝试
string skill = ((TextBox)(Page.FindControl("TextBox" + i.ToString()))).Text;