2015-05-13 103 views
1

我在运行时构建了一些按钮,并且我想为每个按钮分配一个标签。为一个按钮指定一个标签并检索它

我愿意这样做

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())); 
+0

我认为这是附加到表单?你所显示的内容可以工作,但你可能想要将你的ID存储在一个隐藏的表单域中,而不是依赖于按钮标签。 – mjw

回答

2

这是因为你想投的Int16int(又名Int32)。

Int16一个是shortInt32int,也Int64long

尝试在Int32要么把或拉出一个Int16

拉出为Int16

dtProducts = LoadProducts((Int16)(sender as Button).Tag);  

或者把尽可能Int32

btnCategorie.Tag = Int32.Parse(row["IDSubcategorie"].ToString()); 

你只需要一个上面,不是两个,否则你有和以前一样的问题。

我推荐使用Int32/int,除非你有特定的需求Int16 - 在这个计算机的时代,你不会获得太多的好处。

+0

谢谢,我错过了那个细节。 – CiucaS

相关问题