【问题标题】:How to get the name of a button that I want to drag on a panel如何获取要在面板上拖动的按钮的名称
【发布时间】:2015-02-21 06:37:17
【问题描述】:

我是 C# 和 WinForm 的新手,我在互联网上搜索过,但找不到我正在寻找的解决方案。如果有人请帮助我,那就太好了。

这是我的问题-


我已经创建了一个类似上图的表单。有3个面板-

  1. 输入面板(它实际上包含一些按钮)
  2. 拖动面板(用户将按钮从“输入面板”拖动到此面板)
  3. 输出面板(它将告诉“拖动面板”中的按钮名称)

    • 如果用户拖动多个按钮,则输出面板也会显示多个名称。

【问题讨论】:

  • 可以通过.Name属性获取被拖拽的按钮名称。 string draggedName = draggedButton.Name;
  • 当且仅当名称 property 是他想要的名称时才成立。有些人寻找可能有所不同的变量的名称。要获得该名称,必须使用反射

标签: c# winforms visual-studio drag-and-drop


【解决方案1】:

尝试类似:

private void UpdateLabel()
{
    label1.Text = "";
    foreach (Control c in DragPanel.Controls)   //Going through all controls in the panel
    {
        if (c.GetType().Name == "Button")        // Checking whether the control is a Button
            label1.Text += Environment.NewLine+ ((Button)c).Text;     //Updating the label
    }
}

当按钮被拖到面板时调用函数UpdateLabel()。

说明:

此代码将选择 DragPanel 中的所有控件,如果是 Button,它将获取 Text 属性的值并在新行中附加到标签。

编辑:

您可以将Button 替换为您想要的控件名称(例如:TextBox)。

foreach (Control c in DragPanel.Controls)   
{
    if (c.GetType().Name == "TextBox")     
    {
          label1.Text += Environment.NewLine + ((TextBox)c).Text;     
    }
}

如果你想获取面板中的所有控件,那么你可以这样做:

foreach (Control c in DragPanel.Controls) 
{
      label1.Text += Environment.NewLine + c.Text;  
}

【讨论】:

  • 这行得通。但是,如果我想获得除 Button 之外的其他控件,我是否必须将“Button”替换为 (例如 TextBox)??
  • @RupamBhaduri:是的,当然。您可以在那里使用任何控件名称。如果要列出所有控件,则可以删除 if 语句。我会更新我的答案。
  • 请举个例子。那么文本 label1.Text += Environment.NewLine+ ((Button)c).Text 会起作用吗?因为有 ((Button)c).Text
【解决方案2】:
var dragged = dragPanel.Controls
                       .OfType<typeof(Button)>()
                       .Select(button => button.Text);

【讨论】:

  • @NikolayKostov:有什么需要解释的?此代码选择所有按钮(文本),然后您可以根据需要输出它....
  • 此代码不起作用,因为我无法找到此代码的用途。不过谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多