简体   繁体   English

DataGridView 插入后不更新显示

[英]DataGridView not updating display after insert

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (transaction_idTextBox.Text == "" || lastnameTextBox.Text == "" || firstnameTextBox.Text == "" || middlenameTextBox.Text == "" || txtYear.Text == "" || txtDoI.Text == "" || txtPoI.Text == "" || txtAddress.Text == "" || CB_Sex.Text == "" || txtCS.Text == "" || txtDoB.Text == "" || txtPoB.Text == "" || txtAmount.Text == "")
            {
                MessageBox.Show("All Fields Are Compulsory");
            }
            else
            {
                SqlCommand cmdinsert = new SqlCommand("Insert into [Transaction] values( ' " + transaction_idTextBox.Text + " ','" + lastnameTextBox.Text + "','" + firstnameTextBox.Text + " ','" + middlenameTextBox.Text + "','" + txtYear.Text + "','" + txtDoI.Text + "','" + txtPoI.Text + "','" + txtAddress.Text + "','" + CB_Sex.Text + "','" + txtCS.Text + "','" + txtDoB.Text + "','" + txtPoI.Text + "','" + txtAmount.Text + "' )", con);
                con.Open();
                cmdinsert.CommandType = CommandType.Text;
                cmdinsert.ExecuteNonQuery();
                MessageBox.Show("Data Added");
                transactionDataGridView.Update();
                transactionDataGridView.Refresh();
                transaction_idTextBox.Text = "";
                lastnameTextBox.Text = "";
                firstnameTextBox.Text = "";
                middlenameTextBox.Text = "";
                txtYear.Text = "";
                txtDoI.Text = "";
                txtPoI.Text = "";
                txtAddress.Text = "";
                CB_Sex.Text = "";
                txtCS.Text = "";
                txtDoB.Text = "";
                txtPoB.Text = "";
                txtAmount.Text = "";
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
        }
    }

For first : Add "LoadData();"首先:添加“LoadData();” at the end of Your code在您的代码末尾

Secondly add this to populate DataGridView:其次添加这个来填充 DataGridView:

    public void LoadDataEQ()
    {
        DataTable AllDataTable = new DataTable();
        string SqlCommand = "SELECT * FROM Transaction";
        SqlDataAdapter SQLDA = new SqlDataAdapter(SqlCommand , con);
        SQLDA.Fill(AllDataTable);
        SQLDA.Dispose();
        dataGridView1.DataSource = AllDataTable;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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