我在運行時構建了一些按鈕,並且我想爲每個按鈕分配一個標籤。爲一個按鈕指定一個標籤並檢索它
我願意這樣做
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