为什么我看到的是System.Windows.Forms.文本框,文本:每次我点击插入按钮

本文关键字:文本 按钮 插入 我看 System Forms Windows 为什么 | 更新日期: 2023-09-27 17:54:15

每次我点击插入这个代码将插入好,但当我打开访问数据库,这是如何把每个单元格System.Windows.Forms。文本框,文本:这是我的插入代码

private void button1_Click(object sender, EventArgs e)
{
    System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data source= C:'Users'user'Documents'Visual Studio 2010'Projects'WindowsFormsApplication1'WindowsFormsApplication1'crt_db.accdb";
    conn.Open();
    String my_querry = (@"INSERT INTO System (Name, Address, Conperson, Scope_of_certification, Certification, Date_issued,
                        Dateofsurv, Dateofrecerti, Remark, certi_fee)
                 VALUES ('" + txtName + "','" + txtAddress + "','" + txtConperson + "','" + txtscoperofcerti + "','" + txtcertification + "','" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "','" + dateTimePicker2.Value.ToString("MM/dd/yyyy") + "','" + dateTimePicker3.Value.ToString("MM/dd/yyyy") + "','" + txtRemark + "','" + txtcertfee + "')");
    OleDbCommand cmd = new OleDbCommand(my_querry, conn);
    cmd.ExecuteNonQuery();
    conn.Close();
}

为什么我看到的是System.Windows.Forms.文本框,文本:每次我点击插入按钮

您直接访问TextBox控件,您需要访问其Text属性才能访问其内容。

替换:

txtName 
与这个:

txtName.Text

其他控件相同。

建议:您的查询是开放的SQL注入攻击使用参数化查询来避免它们

请停止使用连接查询字符串,因为这将使您对SQL注入攻击开放,并导致多个其他问题,例如当传递DateTime值时!使用像这样的参数化查询。另外,请注意您需要在数据库中插入TextBox.Text,而不是TextBox以获得正确的值:

private void button1_Click(object sender, EventArgs e)
{
    System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
    @"Data source= C:'Users'user'Documents'Visual Studio 2010'Projects'WindowsFormsApplication1'WindowsFormsApplication1'crt_db.accdb";
    conn.Open();
    String my_querry = @"INSERT INTO System (Name, Address, Conperson, Scope_of_certification, Certification, Date_issued,
                        Dateofsurv, Dateofrecerti, Remark, certi_fee)
                 VALUES (@name, @address, @conPerson, @scope, @cert, @dateIssued, ...");
    OleDbCommand cmd = new OleDbCommand(my_querry, conn);
    cmd.Parameters.AddWithValue("@name", txtName.Text);
    cmd.Parameters.AddWithValue("@address", txtAddress.Text);
    ...
    cmd.Parameters.AddWithValue("@dateIssued", dateTimePicker1.Value);
    ...
    cmd.ExecuteNonQuery();
    conn.Close();
}

还有:请习惯将日期存储为DateTimeDate,而不是文本。还请注意我如何使用DateTime.Now作为参数值。它适用于所有数据类型。在您的情况下(直到您更改为DateTime/Date列类型),您需要使用dateTimePicker1.Value.ToString("MM/dd/yyyy")