简体   繁体   中英

Update the list view after adding a new item in C# WinForms

I have a ListView and it binds data from the database. This is the code to bind date from database. After adding a new item, the list view is not updated. But in the database, the table gets updated. The code I used to bind the list view:

public void BindIncomeExpense()
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
    SqlCommand command = con.CreateCommand();
    command.CommandText = "sp_getAllIncomeExpense";

    SqlDataAdapter da = new SqlDataAdapter(command);
    DataTable dataTable = new DataTable();
    da.Fill(dataTable);

    for(int i = 0; i < dataTable.Rows.Count; i++)
    {
        DataRow drow = dataTable.Rows[i];
        // Only row that have not been deleted
        if(drow.RowState != DataRowState.Deleted)
        {
            // Define the list items
            ListViewItem lvi = new ListViewItem(drow["Description"].ToString());
            lvi.SubItems.Add(drow["Category"].ToString());
            lvi.SubItems.Add(drow["Amount"].ToString());
            lvi.SubItems.Add(drow["Date"].ToString());

            listView9.Items.Add(lvi);
        }
    }
    con.Close();
}

And to add new item

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("sp_saveIncomeExpense", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@id", comboBox12.SelectedValue);
    cmd.Parameters.AddWithValue("@description", textBox1.Text);
    cmd.Parameters.AddWithValue("@amount", textBox2.Text);
    cmd.Parameters.AddWithValue("@date", dateTimePicker12.Value);
    con.Open();
    int i = cmd.ExecuteNonQuery();

    con.Close();

    if(i != 0)
    {
        MessageBox.Show("Data Saved Successfully");
        this.Close();
    }

    Main frm = new Main();
    frm.BindIncomeExpense();
}

And I can't understand why the storedprocedure didn't return the lastly added data to the listview. In the database when I execute the sp, it returns the last data also.

Main frm = new Main();
This might be the problem. You are creating new instance of form. This might not be the same that is being displayed on screen. Use the same instance that you used to display the form on screen.

For example, somewhere in your code you have already loaded Main form using

Main frmOriginal = new Main();
frmOriginal.Show();// or ShowDialog or Application.Run

Your frmOriginal instance should be accessible while calling binding method. Your new code should be something like:

//Main frm = new Main();//Do not use this
frmOriginal.BindIncomeExpense();//Use the instance of form that is already being displayed.

Edit:

Based on your comment, you need to pass instance of Main form to IncomeExpense form.
Following code will be on Main form to create IncomeExpense form:

IncomeExpense incomeExpense = new IncomeExpense();
incomeExpense.ShowDialog(this);

On IncomeExpense form:

//Main frm = new Main();//Do not use this
this.Owner.BindIncomeExpense();

I got the answer. I used

if(System.Windows.Forms.Application.OpenForms["Main"] != null)
        {
            (System.Windows.Forms.Application.OpenForms["Main"] as Main).BindIncomeExpense();
        }

to call the current instance of the Main form. Now it is working according to my requirement. Complete code in the IncomeExpense form to save the data is

private void button1_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-U1OP1S9\SQLEXPRESS;Initial Catalog=PaintStores;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("sp_saveIncomeExpense", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@id", comboBox12.SelectedValue);
        cmd.Parameters.AddWithValue("@description", textBox1.Text);
        cmd.Parameters.AddWithValue("@amount", textBox2.Text);
        cmd.Parameters.AddWithValue("@date", dateTimePicker12.Value);
        con.Open();
        int i = cmd.ExecuteNonQuery();

        con.Close();

        if (i != 0)
        {
            MessageBox.Show("Data Saved Successfully");
            this.Close();
        }

        if(System.Windows.Forms.Application.OpenForms["Main"] != null)
        {
            (System.Windows.Forms.Application.OpenForms["Main"] as Main).BindIncomeExpense();
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

Thank you all for your help. Regards.

请再次绑定数据库中的数据以获取新数据,即在将数据保存到数据库后简单地调用绑定数据的函数

请确保sp_getAllIncomeExpense正确返回数据。

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