c# - 将标签分配给按钮并检索它

标签 c# visual-studio-2010

我在运行时构建了一些按钮,我想为每个按钮分配一个标签。

我就是这么做的

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 是一个 shortInt32int,也是 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/

相关文章:

visual-studio-2010 - 在 VS2010 中更改解决方案项的位置

visual-studio-2010 - VS2010 - HLSL 智能感知?

c# - VS2010 - 找不到引用的组件 'X'。 - 禁用自动 "add reference"

c# - LINQ 查询返回错误 "The expected type was ' System.Int3 2' but the actual value was null."

visual-studio - 如何强制 Visual Studio 在遇到第一个错误时停止构建?

c# - Crystal Reports 中的组树 PDF 导出

c# - 根据用户时区的 UTC 时区更改计算

c++ - 双线性图像采样不可重现的访问冲突

c# - 无法仅在 'Install' 上验证 WiX 条件

c# - 调用基于异步任务的 WCF 方法是利用 I/O 完成端口还是线程池线程来调用延续?