将文本框中的数据插入SQL Server数据库

时间:2017-10-04 18:52:50

标签: c# sql-server

我不知道问题出在哪里。我试图将数据从文本框插入到数据库中,我收到错误,如下所示。

这是我的代码

private void but_Add_Click(object sender, EventArgs e)
{
    String query = "INSERT INTO Tbl_Cashier (FName, MName, LName, Address, ContactNo, Email, Age, Gender, Password, role) VALUES (@FName, @MName, @LName, @Address, @ContactNo, @Email, @Age, @Gender, @Password, @role)";

    using (SqlConnection connection = new SqlConnection(connectionString1))
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        connection.Open();

        command.Parameters.AddWithValue("@FName", txb_Fname);
        command.Parameters.AddWithValue("@MName", txb_Mname);
        command.Parameters.AddWithValue("@LName", txb_Lname);
        command.Parameters.AddWithValue("@Address", txb_Address);
        command.Parameters.AddWithValue("@ContactNo", txb_ContactNo);
        command.Parameters.AddWithValue("@Email", txb_Email);
        command.Parameters.AddWithValue("@Age", txb_Age);
        command.Parameters.AddWithValue("@Gender", txb_Gander);
        command.Parameters.AddWithValue("@Password", txb_Password);
        command.Parameters.AddWithValue("@role", txb_Role);

        command.ExecuteNonQuery();
        command.ExecuteScalar();
        connection.Close();
    }
}

我得到的错误是:

  

未处理的类型' System.ArgumentException'发生在System.Data.dll

中      

其他信息:从对象类型System.Windows.Forms.TextBox到已知的托管提供程序本机类型不存在映射。

1 个答案:

答案 0 :(得分:5)

您需要添加.Text结束控件。

command.Parameters.AddWithValue("@FName", txb_Fname.Text);
command.Parameters.AddWithValue("@MName", txb_Mname.Text);
command.Parameters.AddWithValue("@LName", txb_Lname.Text);
command.Parameters.AddWithValue("@Address", txb_Address.Text);
command.Parameters.AddWithValue("@ContactNo", txb_ContactNo.Text);
command.Parameters.AddWithValue("@Email", txb_Email.Text);
command.Parameters.AddWithValue("@Age", txb_Age.Text);
command.Parameters.AddWithValue("@Gender", txb_Gander.Text);
command.Parameters.AddWithValue("@Password", txb_Password.Text);
command.Parameters.AddWithValue("@role", txb_Role.Text);