-5
private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection();

        con.ConnectionString = @"Data Source=YUVV-PC\SQLEXPRESS;Initial Catalog=barcode;Integrated Security=True";
        con.Open();

        //MessageBox.Show("connection open");

        SqlDataAdapter ada = new SqlDataAdapter();
        //ada.SelectCommand = new SqlCommand("select * from barcode", con);
        ada.MissingSchemaAction = MissingSchemaAction.AddWithKey;
        ada.InsertCommand = new SqlCommand("INSERT INTO barcode (bcd) " +
    "VALUES (@bcd)", con);
        ada.InsertCommand.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
        ada.SelectCommand = new SqlCommand("select bcd from barcode", con);

        DataSet ds = new DataSet();
        ada.Fill(ds, "barcode");
        dataGridView1.DataSource = ds.Tables[0].DefaultView;
    }
4

1 回答 1

1

您有 2 个选项来修改您的代码,如下(在 之后con.Open()):

ada.InsertCommand.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
//add this line
//without it you are never executing your `InsertCommand`.
ada.InsertCommand.ExecuteNonQuery();

ada.SelectCommand = new SqlCommand("select bcd from barcode", con);
...

或者,您可以使用SqlCommand这样的:

using (var cmd = new SqlCommand("INSERT INTO barcode (bcd) VALUES (@bcd)", con))
{
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.Add("@bcd", SqlDbType.NChar, 20,"bcd").Value = textBox1.Text;
    cmd.ExecuteNonQuery();
}

SqlDataAdapter ada = new SqlDataAdapter();
//ada.SelectCommand = new SqlCommand("select * from barcode", con);
ada.MissingSchemaAction = MissingSchemaAction.AddWithKey;

ada.SelectCommand = new SqlCommand("select bcd from barcode", con);

DataSet ds = new DataSet();
ada.Fill(ds, "barcode");
dataGridView1.DataSource = ds.Tables[0].DefaultView;

我还建议在您的和实例using周围使用语句,以确保正确处理所有资源。SqlConnectionSqlDataAdapter

于 2013-02-10T10:51:33.397 回答