我有一个ListView
,它绑定了数据库中的数据。这是绑定数据库日期的代码。添加新项目后,列表视图不会更新。但是在数据库中,表已更新。我用来绑定列表视图的代码:
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();
}
并添加新项目
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();
}
而且我不明白为什么存储过程没有将最后添加的数据返回到列表视图。当我执行sp时,在数据库中,它也返回最后一个数据。
最佳答案
Main frm = new Main();
这可能是问题所在。您正在创建表单的新实例。这可能与屏幕上显示的内容不同。使用与您在屏幕上显示表单相同的实例。
例如,在代码中的某处,您已经使用以下命令加载了Main
表单
Main frmOriginal = new Main();
frmOriginal.Show();// or ShowDialog or Application.Run
您的
frmOriginal
实例在调用绑定方法时应该可以访问。您的新代码应类似于:
//Main frm = new Main();//Do not use this
frmOriginal.BindIncomeExpense();//Use the instance of form that is already being displayed.
编辑:
根据您的评论,您需要将
Main
表单的实例传递给IncomeExpense
表单。以下代码将在
Main
表单上创建IncomeExpense
表单:IncomeExpense incomeExpense = new IncomeExpense();
incomeExpense.ShowDialog(this);
在
IncomeExpense
形式上://Main frm = new Main();//Do not use this
this.Owner.BindIncomeExpense();
关于c# - 在C#WinForms中添加新项目后更新 ListView ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44261024/