简体   繁体   中英

Insert data into an SQL Server 2008 table from a form in C#

This is what I have done:

protected void btnsave_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=user-ade4de77d3;Initial Catalog=test;Persist Security Info=True;uid=sa;pwd=sql2008");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    con.Open();
    cmd.CommandText = ("INSERT  into person VALUES (@empid,@name,@sex,@mstatus,@empstat,@dob,@doh,@dor,@dot)");
    cmd.Parameters.AddWithValue("@empid", txtid.Text);
    cmd.Parameters.AddWithValue("@name", txtnam);
    cmd.Parameters.AddWithValue("@sex", dpsex.SelectedValue);
    cmd.Parameters.AddWithValue("@mstatus", dpmstat.SelectedValue);
    cmd.Parameters.AddWithValue("@empstat", dpstatus.SelectedValue);
    cmd.Parameters.AddWithValue("@dob", txtdob.Text );
    cmd.Parameters.AddWithValue("@doh", txtdoh.Text );
    cmd.Parameters.AddWithValue("@dor", txtdor.Text );
    cmd.Parameters.AddWithValue("@dot", txtdot.Text );
    cmd.ExecuteNonQuery();
    con.Close();
}

I'm getting an error like this:

No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.

How do I clear this error?

You need to change the following line:

cmd.Parameters.AddWithValue("@name", txtnam.Text);

as your version is missing the .Text off the end.

You have forgotten to add the .Text at this line:

cmd.Parameters.AddWithValue("@name", txtnam);

change it to:

cmd.Parameters.AddWithValue("@name", txtnam.Text);

Your line

cmd.Parameters.AddWithValue("@name", txtnam);

should be

cmd.Parameters.AddWithValue("@name", txtnam.text);

I believe the problem is this line:

cmd.Parameters.AddWithValue("@name", txtnam);

You're trying to set the value of the parameter to the textbox itself - not its .Text property!

Use this instead:

cmd.Parameters.AddWithValue("@name", txtnam.Text);

您可能需要txtnam.Text

cmd.Parameters.AddWithValue("@name", txtnam.Text); 

The error is simple. You forgot to get the text property on txtnam , so you are passing the entire textbox object instead of its value.

txtnam.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM