我在运行时构建了一些按钮,并且我想为每个按钮分配一个标签。为一个按钮指定一个标签并检索它
我愿意这样做
private void CreateCategory(DataTable dt)
{
int top = 0;
int left = 0;
string color = "";
foreach (DataRow row in dt.Rows)
{
// MessageBox.Show(row["Denumire"].ToString());
// List<Button> buttons = new List<Button>();
Button btnCategorie = new Button();
color = row["Culoare"].ToString();
btnCategorie.Text = row["Denumire"].ToString();
btnCategorie.BackColor = rbgToColor(color);
btnCategorie.Top = 0 + top;
btnCategorie.Left = 0 + left;
btnCategorie.Width = 120;
btnCategorie.Height = 120;
btnCategorie.FlatStyle = FlatStyle.Popup;
btnCategorie.Tag = Int16.Parse(row["IDSubcategorie"].ToString());
// buttons.Add(newButton);
tabCategorii.Controls.Add(btnCategorie);
btnCategorie.Click += new System.EventHandler(this.btnCategorii_Click);
left = left + 120;
if (left % 600 == 0)
{
top = top + 120;
left = 0;
}
}
}
现在我试着找回这样
DataTable dtProducts = new DataTable();
dtProducts = LoadProducts((int)(sender as Button).Tag);
CreateProducts(dtProducts, (sender as Button).BackColor, pnlProduse);
试图转换
Additional information: Specified cast is not valid.
我已经在此抛出一个错误设法做到这一点,但它看起来像一个黑客,我不喜欢它,有没有更好的方式来检索我的标记值?
dtProducts = LoadProducts(Int32.Parse((sender as Button).Tag.ToString()));
我认为这是附加到表单?你所显示的内容可以工作,但你可能想要将你的ID存储在一个隐藏的表单域中,而不是依赖于按钮标签。 – mjw