I have below model class in c# window application. I have form controls which I want to assign values to model properties after form validation. I have many more controls and many controls are the same. So instead of validating each control separate I want to loop the same controls and validate then in for loop.
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()
{
}
}
}
and below is my form code.
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)
{
}
}
}
In my ValidateForm() I want some thing like below.
foreach (Control ctrl in Controls.OfType<TextBox>())
{
if(ctrl.Text!="")
{
customermodel[ctrl.Name] = ctrl.text;
}
}
In the above all is good. The problem is at
customermodel[ctrl.Name] = ctrl.text;
[..]on a custom object like in this line:customermodel[ctrl.Name] = ctrl.text;you would need to override the indexing operator. Since I don't see that piece of code in yourCustomerModelclass. This should lead to a compilation error. This compilation error can be researched in your favourite search engine.