[Gabriel的专栏] 用C#如何遍历一个窗体中的某一种控件

获取Winform窗体或Panel下包含的所有控件、根据控件名称获取指定控件 一、实现效果 在 Winform中窗体(Form)就像一个容器,可以包含所有的控件(比如:panel、button、textedit等控件);如果把窗体看做是 Winform 中最大的容器,那么Panel可以看做第二,Panel控件则是专门用于界面的排版布局,相当于 Web 开发中的层(div),几乎所有控件都可以包含到 Panel 中,包括窗体。 ①获取到指定窗体下的所有控件; ②获取到指定Panel下的所有控件; ③获取到窗体下的所有TextEdit类型控件; ④根据控件名称获取到该控.. 阅读详情

/* 作者:耿奕廷    版权所有,转载时请注明出处及作者    */

假设我要遍历所有的Label控件.我们知道一个窗体中的所有控件都是Form.Controls中的成员,想要得到窗体中的所以成员,可以用foreach来遍历Controls属性中的对象。注意,Controls属性中包含的对象都是以Control基类形式存在的,这就是说我们只能用foreach(Control temp in this.Controls)来遍历。对于任何一个由Control派生来的类,或者说是所以控件,可以用其 GetType()函数来得到控件的类型。如果要判判断具体类型需要将类型转为字符串:tempControl.GetType().ToString()    它得到的是一个控件的完整名字,如:System.Windows.Forms.Label。

现在我们考虑另一种情况,在控件中,有一些控件有子控件如 Panel ,GroupBox,而这些控件中又可能包含其它的Panel,GroupBox,所以我们必须判断出这些“母控件”,并用递归方法对其中的控件遍历!

代码如下,在窗体中至少有一个LISTBOX和 一个按钮,注意每个函数接受的参数类型。

 

private void GetLabeinP(Panel temp)     //对panel进行遍历的函数
  {
   foreach(Control tempcon in temp.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }
  }
  private void GetLabeinG(GroupBox temp)   //对GroupBox遍历
  {
   foreach(Control tempcon in temp.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }
  }

  private void button1_Click_1(object sender, System.EventArgs e)  //按钮的代码
  {
   this.listBox1.Items.Clear();
   foreach(Control tempcon in this.Controls)
   {
    switch(tempcon.GetType().ToString())
    {
     case "System.Windows.Forms.Label":
      this.listBox1.Items.Add(tempcon.Name);
      break;
     case "System.Windows.Forms.Panel":
      this.GetLabeinP((Panel)tempcon);
      break;
     case "System.Windows.Forms.GroupBox":
      this.GetLabeinG((GroupBox)tempcon);
      break;

    }
     
   }  

  
  }

VScode - 从入门到精通:高效开发环境搭建指南 本文是一份全面的VSCode高效开发环境搭建指南。从选择理由、安装配置、核心插件推荐到个性化设置与高效技巧,详细讲解了如何将这款轻量级编辑器武装成强大的开发工具。重点介绍了GitLens、Prettier、Live Server等必备插件,以及通过用户设置、代码片段和快捷键打造专属高效工作流的方法,帮助开发者从入门到精通。 阅读详情

相关推荐

OpenClaw安装方式那么多,但建议大家还是用云厂商吧

OpenCloud的安装方式多样,包括One-liner、npm、pnpm和Hackable等。One-liner提供高效的单行命令安装;npm和pnpm作为Node.js包管理工具,分别提供常规和高性能的安装选项;Hackable则支持定制化安装。不同系统(macOS、Windows)和终端(PowerShell、CMD)的操作步骤各有特点,用户需根据自身技术背景选择合适的安装方式。官方推荐使用闲置计算资源或云部署方案以获得更佳体验。

涛涛讲AI 1398

用C#如何遍历一个窗体中的某一种控件

/* 作者:耿奕廷    版权所有,转载时请注明出处及作者    */ 假设我要遍历所有的Label控件.我们知道一个窗体中的所有控件都是Form.Controls中的成员,想要得到窗体中的所以成员,可以用foreach来遍历Controls属性中的对象。注意,Controls属性中包含的对象都是以Control基类形式存在的,这就是说我们只能用foreach(Control temp i

Gabriel的专栏 1万+

OpenMV模块视觉测距(避障)+颜色识别+TFT-LCD显示(实现原理与代码分析)

上图所示代码实际运行的帧率比较低,主要原因有以下两个:1.硬件问题,博主使用的版本比较低,可以尝试使用高版本OpenMV2.图像滤波问题。之前加入图像滤波是想提高色块识别的准确性,但是相应的运算速度也会下降。

ediykk的博客 1万+

wpf中遍历界面控件的方法

摘要://////遍历界面中的所有控件//////privatevoidSetNotEditable(UIElementCollectionuiControls){foreach(UIElementelementinuiControls){if(elementisTextBox){(elementasT

weixin_41883890的博客 1439

高动态范围结构光三维测量技术:从多曝光融合到深度学习的演进与应用

本文深入探讨了高动态范围结构光三维测量技术的演进与应用,从传统的多曝光融合技术到深度学习驱动的创新方案。通过工业案例展示了该技术在提升测量精度和效率方面的显著优势,特别是在处理高反光、复杂表面时的突破性表现。文章还提供了针对不同工业场景的技术选型指南,帮助工程师优化三维测量解决方案。

weixin_29063979的博客 293

闲人闲谈PS之十二——WBS-BOM在装备制造项目中的实战解析

本文深入解析了WBS-BOM在装备制造项目中的核心应用。针对按订单设计/生产的行业痛点,WBS-BOM作为项目专属物料清单,完美连接SAP PS与PP模块,确保MRP能基于项目进行精准物料需求计算,实现从设计到生产的全链路项目化跟踪与管理。

weixin_29284885的博客 399

WinForm递归遍历控件

public static void GetControl(Control.ControlCollection ctc)         {             foreach (Control ctl in ctc)             {                 //当窗体上的控件有子控件时,需要用递归的方法遍历,才能全部列出窗体上的控件              

Zh_GY的专栏 2362

【OpenCV-Python】图像的载入、显示和输出(imread()、imshow()、waitKey()、namedWindow()、imwrite())

图像的载入:imread()函数 imread()函数可以用来非常便捷地读取文件中的图片到Opencv中。这个函数一般需要两个参数: (1)载入图片的路径名。如果图像文件在工程文件夹下,可以直接用文件名读取,如“cat.jpg”,否则需要输入完整的访问路径,如“D:\\test\\lena.png”。这里还有几个tips: imread函数中,一个点代表省略当前文件夹路径,两个点则代表回...

M&Q的博客 1397

WPF 随记一

WPF笔记

Wanderer_Night的博客 394

利用ArcGIS创建渔网计算渔网内土地利用占比划分中国北方农牧交错带

依据土地利用数据,根据参考文献划分要求,利用ArcGIS创建渔网对地物进行重分类,划分农业带、牧业带以及农牧交错带。

m0_60672527的博客 3058

【tessy】软件环境配置:Keil C51 Keil uVision UVSC (Default)

本文详细说明了tessy软件如何配置【Keil C51 Keil uVision UVSC (Default)】环境,具体操作步骤和注意事项

qq_37282365的博客 599

c#属性遍历 和获取名称和数值

c#属性遍历 和获取名称和数值

322

Spring AI 实战:第五章、Spring AI本地模型部署之省钱小能手

白嫖的快乐你想象不到经过这番折腾,我们成功实现了零成本使用大模型完全本地运行保障隐私可视化访问Java生态无缝集成但可能有的小伙伴要吐槽,怎么换个底层模型这次就新建一个工程了呢?不能在以前的工程上开发吗?这样也太不优雅了吧~,我知道你很急,但先别急,等下一章节再来解决这个问题。为什么程序员特别喜欢Ollama?因为它就像一只温顺的羊驼——不花钱还能24小时产出代码!

liaokailin的专栏 921

C#Winform拓展控件之Panel

C#Winform拓展控件之Panel

Iawfy_的博客 4265

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

容器panel里控件的遍历顺序排列规则以及如何调整

  在编写Windows窗体应用程序时,我们经常会用到panel容器,一来便于控件排版,而来方便编程。有时候我们将创建好的控件拖入到容器中后,在遍历容器内控件时,发现容器内控件遍历的顺序并不是我们需要的顺序,那怎么办呢? 一、容器内控件的遍历顺序规则   panel容器内的控件遍历顺序为:按加入容器的先后排列的,先加入的遍历顺序在前,后加入的遍历顺序在后。容器内控件的tab顺序和遍历顺序无关。 二...

mengxiangde的博客 1903

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

C# Winform Label 控件

Label 控件是 winform 开发中最常用的一个控件,一般用做显示文本,也有时用做打开链接等操作。

熊思雨的博客 8781

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

C#控件遍历(获取控件名)

C#中,遍历窗体上的控件,并显示在ListBox1中: private void button1_Click(object sender, EventArgs e)         {             listBox1.Items.Clear();             GetControl(this.Controls);         }         private

lockelk的专栏 4221

c#遍历form窗体上的所有控件

//遍历Form上的所有控件foreach (System.Windows.Forms.Control control in this.Controls){ if (control is System.Windows.Forms.Button) { System.Windows.Forms.Button btn = (System.Windows

Cabble_II的专栏 1万+

C#中如何遍历窗口中的控件!

private void button1_Click(object sender, EventArgs e)              {                  listBox1.Items.Clear();                  GetControl(Controls);              }        private void GetControl(Co

布衣者的专栏 1万+

找出窗体中指定控件(WINFORM && WEBFORM)

遍历WINFORM当前窗体所有控件     foreach (Form form in Application.OpenForms)             {                 foreach (Control item in form.Controls)                 {                     if (item is TextBox)

孤独求醉的专栏 2498

C#中GroupBox控件的使用

GroupBox(框架)控件是C#中用来组织其他控件形成一个控件组,它的使用方法为【工具箱】-》【所有Windows窗体】(或者是【容器】列表中)-》【GroupBox】,拖拽到窗体界面中,再将其他控件拖拽到GroupBox中就可以形成一个控件组。当框架移动时,该控件组同时移动,不会产生其他的位移,所以是组织界面的好东西。 它主要有两个属性:Text和Visible。 Text属性代表Grou

wangluojisuan的专栏 4万+

C#中groupBox1控件详细使用方法

C#中groupBox1控件详细使用方法

xiaogongzhu001的博客 5918

C# foreach 遍历问题

可以看到,for 循环并没有因为数组的长度增加而报错,另外,由于添加的内容在 List 的最后一个元素,所以在后面也能正常被遍历处来,这主要是 for 循环的特殊性,下面就来看看是怎么回事。i++ 也不会影响,i++ 的执行条件,原自前面的 i < list.count 这句代码,所以,只要前面不满足条件,i++ 也不会执行。在后面的循环中,都会判断, i 是否 < list.count ,由于我们在执行过程中加了一个元素,所以这里也会 + 1。系统.无效操作异常:“集合已修改;可能无法执行枚举操作。

fkdw27的博客 633

C#根据控件名获取控件

C#根据控件名获取控件 在网上看到的方法主要有两种。 1. string name=“Label” + “1”; foreach (Control item in this.Controls)   {     if (item. Name == name)     { item. Visible = true; } 这种方法虽然可以实现效果,但过于复杂,写得太多。 2.遍历一个parent里面所有控件,根据控件类型获取控件。 这种方法干脆就跟控件名没关系,只跟控件类型有关。 可以这么写: for(int i

newswordbetrue的博客 2699

c# winform 循环遍历界面上的所有控件,foreach,Controls,AllowDrop

C#代码   foreach (System.Windows.Forms.Control control in this.groupBox2.Controls)//遍历groupBox2上的所有控件      {       if (control is System.Windows.Forms.PictureBox)       {        System.Window

而立大叔 1186

C# 在winform中查找控件

/// /// 在winform中查找控件 /// /// /// /// private System.Windows.Forms.Control findControl(System.Windows.Forms.Control control, string controlName) {     Control c1;     foreach (Con

马银伟专栏 1777
上一篇: [SY的专栏]C#WinForm制作异形窗体/控件
下一篇: [懵懂边缘] 用Visual C# 2005创建快捷方式
MaybeHelios
博客等级 码龄21年 65粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值