You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForms C#:如何在通用方法中使用多组ListView与TextBox对象

在WinForms C#中用通用方法关联多组TextBox和ListView控件

你的现有代码传参方式是完全可行的——直接在按钮点击事件中传入对应控件实例,就是正确的用法。因为checkBarcode方法的参数定义就是接收TextBox和ListView类型对象,窗体上的控件本身就是这些类型的实例,直接传递即可。

现有代码的正确性验证

你示例里的写法没有问题:

  • btn_CheckEggBarcode_Click中传入txt_Egg和lst_Products
  • btn_CheckMilkBarcode_Click中传入txt_Milk和lst_Milk
  • btn_CheckChocloteBarcode_Click中传入txt_Choclote和lst_Choclote

运行时这些控件实例会被正确传递到通用方法中,执行清空等逻辑。

优化方案:减少重复点击事件代码

如果后续要增加更多组控件,每个按钮都写单独的点击事件会比较繁琐,可以通过以下方式简化:

1. 定义控件配对类

先创建一个类来存储每组关联的TextBox和ListView:

private class ControlPair
{
    public TextBox InputBox { get; set; }
    public ListView ResultList { get; set; }
}

2. 绑定按钮与控件对

在窗体构造函数或Load事件中,给每个按钮的Tag属性赋值对应的控件对:

public YourFormName()
{
    InitializeComponent();
    
    btn_CheckEggBarcode.Tag = new ControlPair { InputBox = txt_Egg, ResultList = lst_Products };
    btn_CheckMilkBarcode.Tag = new ControlPair { InputBox = txt_Milk, ResultList = lst_Milk };
    btn_CheckChocloteBarcode.Tag = new ControlPair { InputBox = txt_Choclote, ResultList = lst_Choclote };
}

3. 通用点击事件处理方法

把所有按钮的点击事件都绑定到同一个方法:

private void btn_CheckBarcode_Common_Click(object sender, EventArgs e)
{
    Button currentBtn = sender as Button;
    ControlPair pair = currentBtn?.Tag as ControlPair;
    
    if (pair != null && pair.InputBox != null && pair.ResultList != null)
    {
        checkBarcode(pair.InputBox, pair.ResultList);
    }
}

额外建议

  • 若checkBarcode方法仅在当前窗体内部使用,建议将访问修饰符从public改为private,避免外部不必要的调用。
  • 如果不同产品的条码校验逻辑有差异,可以给checkBarcode增加一个产品类型参数(比如枚举),或者从控件的Name属性、Tag的额外字段中获取标识,来执行对应逻辑。

内容的提问来源于stack exchange,提问作者Cooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:37:23