我在运行时构建了一些按钮,我想为每个按钮分配一个标签。
我就是这么做的
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()));
最佳答案
这是因为您尝试将 Int16
转换为 int
(又名 Int32
)。
Int16
是一个 short
,Int32
是 int
,也是 Int64
是一个long
。
尝试放入 Int32
或取出 Int16
:
拉出为Int16
:
dtProducts = LoadProducts((Int16)(sender as Button).Tag);
或者输入为Int32
:
btnCategorie.Tag = Int32.Parse(row["IDSubcategorie"].ToString());
您只需要上述其中一项,而不是两者都需要,否则您会遇到与以前相同的问题。
我建议对所有内容都使用 Int32
/int
,除非您对 Int16
有特定需求 - 在当今时代计算,你不会获得太多好处。
关于c# - 将标签分配给按钮并检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223848/