2015-05-13 31 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

相關問題