如何在单击按钮时刷新用户控件中的 tablelayoutpanel 内容

How to refresh tablelayoutpanel contents in user control on button click

我在一个用户控件中有一个按钮单击事件,只要它与字符串数组 ings 中找到的成分相匹配,就会从 tbl_ingredients 中的成分库存中减去 1。

private void btn_confirm_Click(object sender, EventArgs e, string[] ings)
{
   foreach (string s in ings)
   {
      string qry = "UPDATE tbl_ingredients SET inv_stock = inv_stock -1 WHERE inv_name = '" + s + "'";
      SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
      myCommand.ExecuteNonQuery();
   }
}

以及在另一个用户控件中动态创建的 table 布局面板(用于显示所有成分及其各自的总库存)

myConnection = new SQLiteConnection("Data Source=database.sqlite3");
string qry = "SELECT * FROM tbl_ingredients ORDER BY inv_name";
string qry2 = "SELECT COUNT(*) FROM tbl_ingredients";
SQLiteCommand myCommand = new SQLiteCommand(qry, myConnection);
SQLiteCommand myCommand2 = new SQLiteCommand(qry2, myConnection);

openConnection();
int row = Convert.ToInt32(myCommand2.ExecuteScalar());
SQLiteDataReader result = myCommand.ExecuteReader();
string[] itemname = new string[row];
string[] totalstock = new string[row];
int cnt = 0;
if (result.HasRows)
{
   while (result.Read())
   {
      itemname[cnt] = result["inv_name"].ToString();
      totalstock[cnt] = result["inv_stock"].ToString();
      cnt++;
   }
}
//tlb_inventory is the name of the tablelayoutpanel in windows form
tbl_inventory.ColumnCount = 2;
tbl_inventory.RowCount = row;
tbl_inventory.Controls.Add(new Label() { Text = "Item" }, 0, 0);
tbl_inventory.Controls.Add(new Label() { Text = "Total Stock" }, 1, 0);
for (int i = 1, j = 0; i < row + 1; i++, j++)
{
   tbl_inventory.Controls.Add(new Label() { Text = itemname[j], AutoSize = true }, 0, i);
   tbl_inventory.Controls.Add(new Label() { Text = totalstock[j], AutoSize = true }, 1, i);
}

closeConnection();

每当我点击按钮时,它应该实时更新 table 的内容。问题是我必须重新 运行 程序才能显示 table 的更新内容。是否有功能或其他东西可以使用户控件及其内容在单击按钮后刷新?

首先您需要将名称属性设置为标签控件

 tbl_inventory.Controls.Add(new Label() { Name = "Total_"+ itemname[j], Text = totalstock[j], AutoSize = true }, 1, i);

然后在 foreach 循环内的 button_click 事件中添加:

 Label c = (tbl_inventory.Controls.Find("Total_" + s, true).First() as Label);
 var total = Convert.ToInt32(c.Text);
 c.Text = (total++).ToString();