ASP.Net将数据从表单插入数据库异常

时间:2011-12-17 21:05:25

标签: asp.net database forms insert

我正在尝试将表单中的数据插入到我的数据库中,并且它会抛出此错误:

  

从对象类型System.Web.UI.WebControls.TextBox到已知的托管提供程序本机类型不存在映射。

也许这与我尝试从下拉列表中获取数据这一事实有关,而且我不确定语法是否很棒。

以下是代码:

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
        conn.Open();

        string titleName = Title.Text;
        string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (@Ganere, @Title , @Descreption) ");

        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        cmd.Parameters.AddWithValue("Title", Title);

        string genre = GenreDropDown.SelectedIndex.ToString();
        cmd.Parameters.AddWithValue("Ganere", GenreDropDown);

        string descp = Descreption.Text;
        cmd.Parameters.AddWithValue("Descreption", Descreption);

        if (titleName == null || genre == null)
        {
            ErrorMessege.Text = "Please fill all of the fields.";
        }
        else
        {
            ErrorMessege.Text = "You have successfully add a movie!";
            cmd.ExecuteNonQuery();
        }

        conn.Close();
    }

2 个答案:

答案 0 :(得分:2)

你 - 我们不会使用任何你有值的变种

    string titleName = Title.Text;
    string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (@Ganere, @Title , @Descreption) ");

    SqlCommand cmd = new SqlCommand(sqlQuery, conn);
    cmd.Parameters.AddWithValue("Title", titlename);

    string genre = GenreDropDown.SelectedIndex.ToString();
    cmd.Parameters.AddWithValue("Ganere", genre);

    string descp = Descreption.Text;
    cmd.Parameters.AddWithValue("Descreption", descp);

    if (titleName == null || genre == null)
    {
        ErrorMessege.Text = "Please fill all of the fields.";
    }
    else
    {
        ErrorMessege.Text = "You have successfully add a movie!";
        cmd.ExecuteNonQuery();
    }

    conn.Close();
}

答案 1 :(得分:1)

问题在于您尝试使用整个文本框作为参数的值。

变化:

cmd.Parameters.AddWithValue("Title", Title);

cmd.Parameters.AddWithValue("Title", Title.Text);