winform control batch assignment

Last time I was in the background Form form loops, to bind data to the controls, but this is not conducive to simplify the amount of code, and today I will again come out of the code, organized into a class

Reception call:

 Test t = new Test();
            t.SystemName = "SystemName";
            t.ServerAddress = "192.168.1.1";
            this.Fill<Test>(t, this.searchPanel);

Here you can call this directly, I will be inherited from the original form instead of the Form class inherits self-help (to help control class inheritance Form), to help control code in the class, as follows:

 protected void Fill<T>(T dto, Control control)
        {
            JsonCollect.Instance.FillToControl(JsonConvert.SerializeObject(dto), control);
        }
FillToControl is a method designed to control the collection of custom class code is as follows:
  public void FillToControl(string result, Control control)
        {
            JObject JResult = JsonConvert.DeserializeObject<JObject>(result);
            foreach (Control item in control.Controls)
            {
                ExplainElement(JResult, result, item);
            }
        }


  /// <summary>
        /// 将JSON 元素解释道具体的控件上
        /// </summary>
        /// <param name="JResult"></param>
        /// <param name="result"></param>
        /// <param name="uIElement"></param>
        private void ExplainElement(JObject JResult, string result, Control control)
        {
            if (control is TextBox)
            {
                TextBox textBox = control as TextBox;
                if (textBox.Name.ToLower().StartsWith("txt_"))
                {
                    if (JResult != null && JResult[textBox.Name.Replace("txt_", string.Empty)] != null)
                    {
                        textBox.Text = JResult == null ||
                            JResult[textBox.Name.Replace("txt_", string.Empty)] == null ? "" :
                            JResult[textBox.Name.Replace("txt_", string.Empty)].ToString();
                    }
                    else
                    {
                        MessageBox.Show("数据集中没有[{" + textBox.Name.Replace("txt_", string.Empty) + "}]字段,Can not fill . ");
                    }
                }
            }
        }

The above code, the most important thing is to naming rules must be standardized

 

 

Guess you like

Origin www.cnblogs.com/zhixiaoxiao/p/12022070.html