【发布时间】:2020-09-16 07:18:07
【问题描述】:
我在 C# 窗口应用程序中有以下模型类。我有表单控件,我想在表单验证后将值分配给模型属性。我有更多控件,并且许多控件是相同的。因此,我不想单独验证每个控件,而是循环相同的控件并在 for 循环中验证。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TShopLibrary
{
public class CustomerModel
{
public int id { get; set; }
public string Name { get; set; }
public string Contact1 { get; set; }
public string Contact2 { get; set; }
public string RefContact { get; set; }
public decimal ShirtLength { get; set; }
public List<ShirtBottomTypeModel> ShirtBottomType { get; set; } = new List<ShirtBottomTypeModel>();
public decimal Sleeve { get; set; }
public decimal Shoulder { get; set; }
public decimal Chest { get; set; }
public decimal ShirtBottom { get; set; }
public decimal ShalwarLength { get; set; }
public decimal ShalwarWidth { get; set; }
public decimal ShalwarBottom { get; set; }
public decimal ShalwarBottomOpening { get; set; }
public List<NeckTypeModel> NeckType { get; set; } = new List<NeckTypeModel>();
public decimal ChestPlateLength { get; set; }
public decimal ChestPlateWidth { get; set; }
public decimal NeckWidth { get; set; }
public decimal NeckHeight { get; set; }
public decimal Pocket { get; set; }
public List<SewingTypeModel> SewingType { get; set; } = new List<SewingTypeModel>();
public decimal Comments { get; set; }
public decimal CreatedDate { get; set; }
public decimal UpdtedDate { get; set; }
public CustomerModel()
{
}
}
}
下面是我的表单代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TShopLibrary;
namespace TShopUI
{
public partial class AddCustomerForm : Form
{
private CustomerModel customermodel = new CustomerModel();
public AddCustomerForm()
{
InitializeComponent();
}
private bool ValidateForm()
{
}
private void CustomerSaveButton_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
}
}
private void CustomerNameTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
在我的 ValidateForm() 中,我想要一些类似下面的东西。
foreach (Control ctrl in Controls.OfType<TextBox>())
{
if(ctrl.Text!="")
{
customermodel[ctrl.Name] = ctrl.text;
}
}
以上都很好。问题出在
customermodel[ctrl.Name] = ctrl.text;
【问题讨论】:
-
嗨,“这件作品不工作。”这样的句子通常是一个问题级联的开始,以找出所有必要的信息以清楚地了解您的问题。请善待我们,为我们节省时间并详细说明这一事实。究竟发生了什么?
-
乍一看:为了能够在自定义对象上使用
[..],就像这一行:customermodel[ctrl.Name] = ctrl.text;,您需要覆盖索引运算符。因为我在您的CustomerModel类中看不到那段代码。这应该会导致编译错误。这个编译错误可以在你喜欢的搜索引擎中研究。
标签: c#