[英]Accessing Class property using variable in c#
我在 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;
}
}
在以上都很好。 问题是在
客户模型[ctrl.Name] = ctrl.text;
你可以这样做:
var props = typeof(Control).GetProperties();
foreach (var p in props)
{
var value = p.GetValue(control_instance);
if (p.Name == "Text")
Do stuff....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.