ProperyGrid Key Value save to tables and retrieve

Sushil Agarwal 406 Reputation points
2021-04-15T04:12:53.493+00:00

Hellow experts,

I am writing a program to save and retrieve values from datatbase table which contain application properties.

kindly find attached code to do it.

but i am stuck at retrieving values from table and assign them to propertygrid properties.

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Data.SqlClient;  
using System.Windows.Forms;  
using KIToolkit;  
using System.Xml.Serialization;  
using System.IO;  
using System.Threading.Tasks;  
using System.Net;  
using System.Reflection;  
  
namespace Kings.ERP  
{  
    public partial class AppConfigSetUp : FormTabSSRS  
    {  
        public AppConfigSetUp()  
        {  
            InitializeComponent();  
        }  
        private object o0,o1;  
        private BindingSource bs;  
        private DataSet ds = new DataSet();  
        private void AppConfig_Load(object sender, EventArgs e)  
        {  
            Keyfield = "id";  
            LoadData();  
            BindControls();  
            bindNavigator1.ActionWhen();  
            DgvFilterManager dgvAppConfigFilter = new DgvFilterManager(dgvAppConfig);  
            //  
            ConfigMgr cm = new ConfigMgr();  
            //  
            Type t = cm.GetType();  
            string fieldName;  
            object propertyValue;  
  
            //https://blogs.msmvps.com/deborahk/iterate-through-the-properties-of-a-class/  
            // Get the type of this instance  
  
            // Use each property of the business object passed in  
            //foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))  
            //{  
            //    //  
            //    // Get the name and value of the property  
            //    fieldName = pi.Name;  
  
            //    // Get the value of the property  
            //    propertyValue = pi.GetValue(cm, null);  
            //    DataRow[] dr = ds.Tables["AppProperties"].Select("Name='" + fieldName + "'");  
            //    if (dr.Length > 0   
            //        && !dr[0]["value"].ToString().Equals("null") )  
            //    {  
            //        //https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue?view=net-5.0  
            //        // Change the instance property value.  
            //        PropertyInfo piInstance = cm.GetProperty(fieldName);  
            //        piInstance.SetValue(cm, dr[0]["value"]);  
            //        //  
            //        //how to cast it to propertytype  
            //        //propertyValue = dr[0]["value"];  
            //        //https://stackoverflow.com/questions/1089123/setting-a-property-by-reflection-with-a-string-value  
            //        PropertyInfo propertyInfo = cm.GetType().GetProperty(fieldName);  
            //        if (propertyInfo != null)  
            //        {  
            //            Type t1 = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;  
            //            object safeValue = (propertyValue == null) ? null : Convert.ChangeType(propertyValue, t); ;  
            //            propertyInfo.SetValue(cm, safeValue, null);  
            //        }  
            //    }  
            //    else  
            //    {  
            //        continue;  
            //    }  
            //}  
  
            //  
            pg.SelectedObject = cm;  
            //  
        }  
  
        private void LoadData()  
        {  
            CursorAdapter c0 = new CursorAdapter();  
            c0.SelectCmd = @"select a.id,a.KeyName,a.Value,a.uppercase,a.validlength,a.columntype  
                            from dbo.AppConfig a";  
            c0.SendUpdate = true;  
            c0.SqlTable = "AppConfig";  
            c0.updatableFieldList = @"KeyName,Value ";  
            c0.keyfields = "id";  
            c0.AutoIncColumns = "id";  
            c0.BuildAdapter(ref ds, ref o0, SqlDataBase.FillType.Data);  
  
            CursorAdapter c1 = new CursorAdapter();  
            c1.SelectCmd = @"select a.Name,a.Value  
                            from dbo.AppProperties a";  
            c1.SendUpdate = true;  
            c1.SqlTable = "AppProperties";  
            c1.updatableFieldList = @"Name,Value ";  
            c1.keyfields = "Name";  
            c1.BuildAdapter(ref ds, ref o1, SqlDataBase.FillType.Data);  
        }  
  
        private void BindControls()  
        {  
            dgvAppConfig.AutoGenerateColumns = false;  
            id.DataPropertyName = "id";  
            SettingName.DataPropertyName = "KeyName";  
            SettingValue.DataPropertyName = "value";  
            columntype.DataPropertyName = "columntype";  
            uppercase.DataPropertyName = "uppercase";  
            ValidLength.DataPropertyName = "validlength";  
  
            bs = new BindingSource(ds, "AppConfig");  
            bindNavigator1.BindingNavigator1.BindingSource = bs;  
            dgvAppConfig.DataSource = bs;  
            DgvSource = ds.Tables["AppConfig"];  
        }  
  
        private void bindNavigator1_BeforeUpdate()  
        {  
            Type t = pg.GetType();  
            string fieldName;  
            object propertyValue;  
  
            //https://blogs.msmvps.com/deborahk/iterate-through-the-properties-of-a-class/  
            // Get the type of this instance  
  
            // Use each property of the business object passed in  
            foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))  
            {  
                // Get the name and value of the property  
                fieldName = pi.Name;  
                // Get the value of the property  
                propertyValue = pi.GetValue(pg, null);  
  
                DataRow[] dr = ds.Tables["AppProperties"].Select("Name='" + fieldName + "'");  
                if (dr.Length>0)  
                {  
                    dr[0]["Value"]= propertyValue == null ? "null" : propertyValue.ToString();  
                }  
                else  
                {  
                    DataRow Ndr = ds.Tables["AppProperties"].NewRow();  
                    Ndr["Name"] = fieldName;  
                    Ndr["Value"] = propertyValue;  
                    ds.Tables["AppProperties"].Rows.Add(Ndr);  
                }  
            }  
        }  
  
        private void bindNavigator1_tblUpdate()  
        {  
            try  
            {  
                SqlDataAdapter adpAppConfig = (SqlDataAdapter)o0;  
                SqlDataAdapter adpProperties = (SqlDataAdapter)o1;  
                adpAppConfig.Update(ds.Tables["AppConfig"]);  
                adpProperties.Update(ds.Tables["AppProperties"]);  
                ds.Tables["AppConfig"].AcceptChanges();  
                ds.Tables["AppProperties"].AcceptChanges();  
            }  
            catch (SqlException ex)  
            {  
                MessageBox.Show(ex.ToString());  
            }  
        }  
  
        private void dgvAppConfig_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)  
        {  
            if (e.Value != null)  
            {  
                if (dgvAppConfig["columntype", e.RowIndex].Value.Equals("S")  
                    && dgvAppConfig["uppercase", e.RowIndex].Value.Equals(true))  
                {  
                    e.Value = e.Value.ToString().ToUpper();  
                    e.FormattingApplied = true;  
                }  
            }  
  
        }  
  
        //Load and save  
        //https://www.codeproject.com/Articles/27326/Load-and-Save-Data-Using-PropertyGrid  
        [Serializable()]  
        public class AppSettings  
        {  
            protected System.Drawing.Size _size;  
  
            public System.Drawing.Size WindowSize  
            {  
                get => _size;  
                set=>_size = value;  
            }  
  
            public static AppSettings Load()  
            {  
                XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));  
                AppSettings retVal=null;  
                TextReader reader;  
                bool fileNotFound=true;  
                try  
                {  
                    reader = new StreamReader("MyAppSettings.xml");  
                }  
                catch (FileNotFoundException ex)  
                {  
                    // Take the defaults  
                    fileNotFound = true;  
                }  
  
                if (fileNotFound)  
                {  
                    retVal = new AppSettings();  
                    retVal.WindowSize = new System.Drawing.Size(600, 600);  
                }  
                else  
                {  
                    // Read it from the file  
                    //11th apr 2021 commented du to error  
                    //retVal = (AppSettings)serializer.Deserialize(reader);  
                    //reader.Close();  
                }  
  
                return retVal;  
            }  
  
            public void Save()  
            {  
                XmlSerializer serializer = new XmlSerializer(typeof(AppSettings));  
                TextWriter writer = new StreamWriter("MyAppSettings.xml");  
                serializer.Serialize(writer, this);  
                writer.Close();  
            }  
        }  
        //load and save  
  
        private static async Task<bool> CheckUrlStatus(string website)  
        {  
            /*  
             * solution from m.s.forum  
            https://learn.microsoft.com/en-us/answers/questions/352019/propertygrid-webadress.html?childToView=354082#answer-354082  
            */  
            return await Task.Run(async () =>  
            {  
                await Task.Delay(1);  
                try  
                {  
                    var request = System.Net.WebRequest.Create(website) as HttpWebRequest;  
                    request.Method = "HEAD";  
                    using (var response = (HttpWebResponse)request.GetResponse())  
                    {  
                        //response = (HttpWebResponse)request.GetResponse();  
                        return response.StatusCode == HttpStatusCode.OK;  
                    }  
                }  
                catch  
                {  
                    return false;  
                }  
            });  
        }  
  
  
        private async void btncheckAddressStatus_Click_1(object sender, EventArgs e)  
        {  
            var webAddress = "https://stackoverflowNotHere.com/";  
  
            btncheckAddressStatus.Enabled = false;  
            try  
            {  
                var results = await CheckUrlStatus(webAddress);  
                MessageBox.Show(results ? "Is valid" : "Is not valid");  
            }  
            finally  
            {  
                btncheckAddressStatus.Enabled = true;  
            }  
        }  
  
        private void btnSaveProperties_Click(object sender, EventArgs e)  
        {  
            Type t = pg.GetType();  
            string fieldName;  
            object propertyValue;  
  
  
            //https://blogs.msmvps.com/deborahk/iterate-through-the-properties-of-a-class/  
            // Get the type of this instance  
  
  
            // Use each property of the business object passed in  
            foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))  
            {  
                // Get the name and value of the property  
                fieldName = pi.Name;  
                propertyValue = pi.GetValue(pg, null);  
  
                DataRow[] dr = ds.Tables["AppProperties"].Select("Name='" + fieldName + "'");  
                if (dr.Length > 0)  
                {  
                    // Get the value of the property  
                    dr[0]["Value"] = propertyValue == null ? "null" : propertyValue.ToString();  
                }  
                else  
                {  
                    DataRow Ndr = ds.Tables["AppProperties"].NewRow();  
                    Ndr["Name"] = fieldName;  
                    Ndr["Value"] = propertyValue;  
                    ds.Tables["AppProperties"].Rows.Add(Ndr);  
                }  
            }  
        }  
    }  
}  
  
//How To Use a type converter with a PropertyGrid control in C#  
//http://csharphelper.com/blog/2014/09/use-a-type-converter-with-a-propertygrid-control-in-c/  
/*  
Getting the Most Out of the .NET Framework PropertyGrid Control  
https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa302326(v=msdn.10)?redirectedfrom=MSDN  
*/  
//paid propertygrid SPG  
//https://marketplace.visualstudio.com/items?itemName=VisualHint.SmartPropertyGridNetforWinForms  
  
//https://www.cyotek.com/blog/creating-a-custom-typeconverter-part-1  
//Use a type converter with a PropertyGrid control in C#  
//http://csharphelper.com/blog/2014/09/use-a-type-converter-with-a-propertygrid-control-in-c/  
  
//validate all properties example  
//https://social.msdn.microsoft.com/Forums/en-US/76193820-fac6-4023-9bc4-d2139ecff0f8/validation-of-property-grid-using-c?forum=csharplanguage  
  
//https://www.levelextreme.com/Home/ShowHeader?Activator=23&ID=38766  
//https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.design.iwindowsformseditorservice?redirectedfrom=MSDN&view=net-5.0  
//use list  
//http://www.reza-aghaei.com/how-to-edit-a-list-of-string-in-propertygrid-using-a-uitypeeditor/  
using System;  
using System.ComponentModel;  
using System.Globalization;  
using System.Reflection;  
using System.Design;  
using System.Windows.Forms;  
using System.Threading.Tasks;  
using System.Net;  
/* Properties Various Settings  
[Browsable(bool)] "To show property or not"  
[ReadOnly(bool)] "Ability to edit property"  
[Category(string)] "Group of property"  
[Description(string)] "Property description, which can be a hint"  
[DisplayName(string)] "Display Name property"  
*/  
  
namespace Kings.ERP  
{  
       
    //SalesLinkedToProduction, 0-No,1-Pre Gst based on oc_link,2-based on issue opening + mfg - sales  
    public enum Sales2Production  
    {  
        Not_Applicable,  
        Oc_Link,  
        Purchase_StockEntry  
    }  
    public enum LcSales  
    {  
        Not_Applicable,  
        Labour_Charges,  
        Against_Grn  
    }  
    public enum Period  
    {  
        Day,  
        Week,  
        Fortnight,  
        Month,  
        Quarter,  
        Half_Year,  
        Year  
    }  
    //https://learn.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-5.0  
    public enum DaysOfWeek  
    {  
        Sunday,  
        Monday,  
        Tuesday,  
        Wednesday,  
        Thursday,  
        Friday,  
        Saturday  
    }  
    [DefaultPropertyAttribute("Name")]  
    public class ConfigMgr  
    {  
        bool  
            Billno_OnSave = false,  
            pvno_OnSave = false,  
            GRNno_OnSave = false,  
            OC_OnSave = false,  
            OA_OnSave = false,  
            IssueSlip_OnSave = false,  
            Purchase_OnGrn = false,  
            SalePackingDetailes = false,  
            bag_packet_qty = false,  
            MdiFixedImage = false,  
            SaleRateFromGRN = false,  
            //  
            BillItemsOnOaItems = false,  
            //  
            BillDateWithoutTime = true,  
            Purchase_po = true,  
            QcOnGrn = true,  
            BillDateEditable = true,  
            AllowNegativeStock = true;  
  
        private string  
            CommonFilePath = @"\\192.168.100.3\erpfiles",  
            PdiIdentityKey = "jaiho",  
            //GSPName = "TaxPro_Production",  
            //AuthUrl = "https://api.taxprogsp.co.in/eivital/v1.03",  
            //BaseUrl = "https://api.taxprogsp.co.in/eicore/v1.03",  
            //EwbByIRN = "https://api.taxprogsp.co.in/eiewb/v1.03",  
            //CancelEwbUrl = "https://api.taxprogsp.co.in/v1.03",  
            UserName = "API_MFPL",  
            Password = "Mfpl@2021",  
            MdiImage = @"..\..\Resources\ChesskingBW.jpg",  
            SlideShowImageFolder = @"C:\Users\Sushil\Pictures",  
            //KI_Email = "******@gmail.com",  
            mail_server = "smtp.gmail.com",  
            Mahindra_Ac = "2-252",  
            BackgroundImage = @"..\..\Resources\chesskingbw.jpg",  
            ServerReportPath = @"http://server/reportserver";  
  
        private int  
            MdiSlideTimer = 10000,  
            s_cashgl = 1,  
            s_debtorgl = 2,  
            s_creditorgl = 3,  
            s_drivergl = 15,  
            CodeGroupInterVal = 25,  
            mail_port = 587,  
            PosDefaultQty = 1;  
  
  
        //Bill To MultiGRn Link at Kimya set it to 2 otheriwse 0,LC Sales, Labour Sales   
        LcSales SaleGrnLinq = LcSales.Not_Applicable;  
        [CategoryAttribute("Sales"), DescriptionAttribute("Labour Charges Work Billing Methods")]  
        public LcSales _SaleGrnLinq  
        {  
            get => SaleGrnLinq;  
            set => SaleGrnLinq = value;  
        }  
        [CategoryAttribute("Sales"), DescriptionAttribute("Verify Production Stock While Billing")]  
        Sales2Production SalesLinkedToProduction = Sales2Production.Not_Applicable;  
        public Sales2Production _SalesLinkedToProduction  
        {  
            get => SalesLinkedToProduction;  
            set => SalesLinkedToProduction = value;  
        }  
  
        [CategoryAttribute("Sales"), DescriptionAttribute("Show Item List Having Order Acceptance Entry")]  
        [TypeConverter(typeof(DyasOfWeekConverter1))]  
        public bool _BillItemsOnOaItems  
        {  
            get => BillItemsOnOaItems;  
            set => BillItemsOnOaItems = value;  
        }  
  
        [CategoryAttribute("Sales"), DescriptionAttribute("Point Of Sale Default Qty.")]  
        public int _PosDefaultQty  
        {  
            get => PosDefaultQty;  
            set => PosDefaultQty = value;  
        }  
  
        [CategoryAttribute("Reports"), DescriptionAttribute("Sql Server Reports Path")]  
        //[Category("Reports")]  
        //[Description("Sql Server Reports Path")]  
        ////[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        ////your poject should refer to System.Design.dll .net 4.0, and using System.Design   
        //[EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        public string _ServerReportPath  
        {  
            get => ServerReportPath;  
            set => ServerReportPath = value;  
        }  
  
        [CategoryAttribute("Ledgers"), DescriptionAttribute("Mahindra A/c. No.")]  
        public string _Mahindra_Ac  
        {  
            get => Mahindra_Ac;  
            set => Mahindra_Ac = value;  
        }  
  
        [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Back Ground Image File")]  
        [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        public string _BackgroundImage  
        {  
            get => BackgroundImage;  
            set => BackgroundImage = value;  
        }  
  
        //[CategoryAttribute("E-Mail"), DescriptionAttribute("Send E-mail From A/c.")]  
        //public string _KI_Email  
        //{  
        //    get =>KI_Email;  
        //    set =>KI_Email=value;  
        //}  
  
        [CategoryAttribute("E-Mail"), DescriptionAttribute("Mail Server Name")]  
        public string _mail_server  
        {  
            get => mail_server;  
            set => mail_server = value;  
        }  
  
        [CategoryAttribute("E-Mail"), DescriptionAttribute("Google Default Port is 587")]  
        public int _mail_port  
        {  
            get => mail_port;  
            set => mail_port = value;  
        }  
  
  
        [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Q.C.Code Each Group Id Gap")]  
        public int _CodeGroupInterVal  
        {  
            get => CodeGroupInterVal;  
            set => CodeGroupInterVal = value;  
        }  
        //https://www.codeproject.com/Articles/6294/Description-Enum-TypeConverter  
        DaysOfWeek WeeklyOff = DaysOfWeek.Sunday;  
        [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Weekly off")]  
        //[TypeConverter(typeof(DyasOfWeekConverter))]  
        public DaysOfWeek _WeeklyOff  
        {  
            get => WeeklyOff;  
            set => WeeklyOff = value;  
        }  
        Period SeePastDataOf = Period.Week;  
        [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Shiow Data Of Past")]  
        //[TypeConverter(typeof(DyasOfWeekConverter))]  
        public Period _SeePastDataOf  
        {  
            get => SeePastDataOf;  
            set => SeePastDataOf = value;  
        }  
        //  
        ImageLayout MdiImageLayout = ImageLayout.Center;  
        [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
        public ImageLayout _MdiImageLayout  
        {  
            get => MdiImageLayout;  
            set => MdiImageLayout = value;  
        }  
  
        [CategoryAttribute("Slide Show"), DescriptionAttribute("Set Show Next Slide in Milliseconds")]  
        public int _MdiSlideTimer  
        {  
            get => MdiSlideTimer;  
            set => MdiSlideTimer = value;  
        }  
  
        [CategoryAttribute("Sales"), DescriptionAttribute("Sales Rate From Grn\nKimaya Engginering")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _SaleRateFromGRN  
        {  
            get => SaleRateFromGRN;  
            set => SaleRateFromGRN = value;  
        }  
  
        [CategoryAttribute("Slide Show"), DescriptionAttribute("set Single Image or Show From Folder")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _MdiFixedImage  
        {  
            get => MdiFixedImage;  
            set => MdiFixedImage = value;  
        }  
  
        [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
        [EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        public string _SlideShowImageFolder  
        {  
            get => SlideShowImageFolder;  
            set => SlideShowImageFolder = value;  
        }  
  
        [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
        [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        public string _MdiImage  
        {  
            get => MdiImage;  
            set => MdiImage = value;  
        }  
  
        [CategoryAttribute("Sales"), DescriptionAttribute("Is Negative Stock allowed ?")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _AllowNegativeStock  
        {  
            get => AllowNegativeStock;  
            set => AllowNegativeStock = value;  
        }  
        [CategoryAttribute("Sales"), DescriptionAttribute("Yes:User Can Changed Bill Date, No:System Date")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _BillDateEditable  
        {  
            get => BillDateEditable;  
            set => BillDateEditable = value;  
        }  
        [CategoryAttribute("GRN"), DescriptionAttribute("Show Q.C. while MAking GRN")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _QcOnGrn  
        {  
            get => QcOnGrn;  
            set => QcOnGrn = value;  
        }  
        [CategoryAttribute("Purchase"), DescriptionAttribute("Check P.O. On Purchase Entry ")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _Purchase_po  
        {  
            get => Purchase_po;  
            set => Purchase_po = value;  
        }  
        [CategoryAttribute("Sales"), DescriptionAttribute("Exclude Time From Bill Date")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _BillDateWithoutTime  
        {  
            get => BillDateWithoutTime;  
            set => BillDateWithoutTime = value;  
        }  
        [CategoryAttribute("Sales"), DescriptionAttribute("Fetch Bag_packet_qty from item master")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _bag_packet_qty  
        {  
            get => bag_packet_qty;  
            set => bag_packet_qty = value;  
        }  
        [CategoryAttribute("Sales"), DescriptionAttribute("Set Packing Details")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _SalePackingDetailes  
        {  
            get => SalePackingDetailes;  
            set => SalePackingDetailes = value;  
        }  
  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _Purchase_OnGrn  
        {  
            get => Purchase_OnGrn;  
            set => Purchase_OnGrn = value;  
        }  
  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No: on Entry, Yes: On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _IssueSlip_OnSave  
        {  
            get => IssueSlip_OnSave;  
            set => IssueSlip_OnSave = value;  
        }  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _OA_OnSave  
        {  
            get => OA_OnSave;  
            set => OA_OnSave = value;  
        }  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _OC_OnSave  
        {  
            get => OC_OnSave;  
            set => OC_OnSave = value;  
        }  
  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _GRNno_OnSave  
        {  
            get => GRNno_OnSave;  
            set => GRNno_OnSave = value;  
        }  
  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _Billno_OnSave  
        {  
            get => Billno_OnSave;  
            set => Billno_OnSave = value;  
        }  
        [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
        [TypeConverter(typeof(YesNoClassConverter))]  
        public bool _pvno_OnSave  
        {  
            get => pvno_OnSave;  
            set => pvno_OnSave = value;  
        }  
  
  
        [Category("Reports")]  
        [Description("Report Folder Path ")]  
        //[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        //your poject should refer to System.Design.dll .net 4.0, and using System.Design   
        [EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
        public string _CommonFilePath  
        {  
            get => CommonFilePath;  
            set => CommonFilePath = value;  
        }  
  
        //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("GSP Name")]  
        //public string _GSPName { get => GSPName; set => GSPName = value; }  
        //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Authentication web URL")]  
        //public string _AuthUrl { get => AuthUrl; set => AuthUrl = value; }  
        //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Base web URL")]  
        //public string _BaseUrl { get => BaseUrl; set => BaseUrl = value; }  
  
        //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("IRN web URL")]  
        //public string _EwbByIRN { get => EwbByIRN; set => EwbByIRN = value; }  
  
        //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Cancell IRN web URL")]  
        //public string _CancelEwbUrl { get => CancelEwbUrl; set => CancelEwbUrl = value; }  
  
        [CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("E-invoice Via GSP User Name")]  
        public string _UserName { get => UserName; set => UserName = value; }  
        [CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("E-invoice Via GSP User Password")]  
        public string _Password { get => Password; set => Password = value; }  
  
        [CategoryAttribute("Ledgers"), DescriptionAttribute("Customer G.L.Id")]  
        public int _s_debtorgl  
        {  
            get => s_debtorgl;  
            set => s_debtorgl = value;  
        }  
        [CategoryAttribute("Ledgers"), DescriptionAttribute("Cash On Hand ID")]  
        public int _s_cashgl  
        {  
            get => s_cashgl;  
            set => s_cashgl = value;  
        }  
        [CategoryAttribute("Ledgers"), DescriptionAttribute("Su
Developer technologies Windows Forms
Developer technologies Transact-SQL
0 comments No comments
{count} votes

6 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-04-15T12:05:52.363+00:00

    Greetings,

    See the following GitHub repository which contains the following project to show how to read and save. Make sure to read the readme.md files online for information about the code.

    • Reads data into a PropertyGrid using list of a class
    • Provides a method to update current selected item in the PropertyGrid
    • Stubbed method for saving all, ran out of time to finish.
    • Using a SQL-Server database with a data script to create and populate the database.

    88264-pg.png

    0 comments No comments

  2. Sushil Agarwal 406 Reputation points
    2021-04-15T13:32:41.153+00:00

    Thanks mam its again a great learning from you.

    from your solution i confusingly undertood that it mappes single rows of a table to propertygird.

    i have attached my appproperties.txt [sql] whose all rows need to be mapped to propertygrid properties .

    can you please guide how best it could be done.

    enter code here

    [//How To Use a type converter with a PropertyGrid control in C#  
    //http://csharphelper.com/blog/2014/09/use-a-type-converter-with-a-propertygrid-control-in-c/  
    /*  
    Getting the Most Out of the .NET Framework PropertyGrid Control  
    https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa302326(v=msdn.10)?redirectedfrom=MSDN  
    */  
    //paid propertygrid SPG  
    //https://marketplace.visualstudio.com/items?itemName=VisualHint.SmartPropertyGridNetforWinForms  
      
    //https://www.cyotek.com/blog/creating-a-custom-typeconverter-part-1  
    //Use a type converter with a PropertyGrid control in C#  
    //http://csharphelper.com/blog/2014/09/use-a-type-converter-with-a-propertygrid-control-in-c/  
      
    //validate all properties example  
    //https://social.msdn.microsoft.com/Forums/en-US/76193820-fac6-4023-9bc4-d2139ecff0f8/validation-of-property-grid-using-c?forum=csharplanguage  
      
    //https://www.levelextreme.com/Home/ShowHeader?Activator=23&ID=38766  
    //https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.design.iwindowsformseditorservice?redirectedfrom=MSDN&view=net-5.0  
    //use list  
    //http://www.reza-aghaei.com/how-to-edit-a-list-of-string-in-propertygrid-using-a-uitypeeditor/  
    using System;  
    using System.ComponentModel;  
    using System.Globalization;  
    using System.Reflection;  
    using System.Design;  
    using System.Windows.Forms;  
    using System.Threading.Tasks;  
    using System.Net;  
    /* Properties Various Settings  
    [Browsable(bool)] "To show property or not"  
    [ReadOnly(bool)] "Ability to edit property"  
    [Category(string)] "Group of property"  
    [Description(string)] "Property description, which can be a hint"  
    [DisplayName(string)] "Display Name property"  
    */  
      
    namespace Kings.ERP  
    {  
           
        //SalesLinkedToProduction, 0-No,1-Pre Gst based on oc_link,2-based on issue opening + mfg - sales  
        public enum Sales2Production  
        {  
            Not_Applicable,  
            Oc_Link,  
            Purchase_StockEntry  
        }  
        public enum LcSales  
        {  
            Not_Applicable,  
            Labour_Charges,  
            Against_Grn  
        }  
        public enum Period  
        {  
            Day,  
            Week,  
            Fortnight,  
            Month,  
            Quarter,  
            Half_Year,  
            Year  
        }  
        //https://learn.microsoft.com/en-us/dotnet/api/system.dayofweek?view=net-5.0  
        public enum DaysOfWeek  
        {  
            Sunday,  
            Monday,  
            Tuesday,  
            Wednesday,  
            Thursday,  
            Friday,  
            Saturday  
        }  
        [DefaultPropertyAttribute("Name")]  
        public class ConfigMgr  
        {  
            bool  
                Billno_OnSave = false,  
                pvno_OnSave = false,  
                GRNno_OnSave = false,  
                OC_OnSave = false,  
                OA_OnSave = false,  
                IssueSlip_OnSave = false,  
                Purchase_OnGrn = false,  
                SalePackingDetailes = false,  
                bag_packet_qty = false,  
                MdiFixedImage = false,  
                SaleRateFromGRN = false,  
                //  
                BillItemsOnOaItems = false,  
                //  
                BillDateWithoutTime = true,  
                Purchase_po = true,  
                QcOnGrn = true,  
                BillDateEditable = true,  
                AllowNegativeStock = true;  
      
            private string  
                CommonFilePath = @"\\192.168.100.3\erpfiles",  
                PdiIdentityKey = "jaiho",  
                //GSPName = "TaxPro_Production",  
                //AuthUrl = "https://api.taxprogsp.co.in/eivital/v1.03",  
                //BaseUrl = "https://api.taxprogsp.co.in/eicore/v1.03",  
                //EwbByIRN = "https://api.taxprogsp.co.in/eiewb/v1.03",  
                //CancelEwbUrl = "https://api.taxprogsp.co.in/v1.03",  
                UserName = "API_MFPL",  
                Password = "Mfpl@2021",  
                MdiImage = @"..\..\Resources\ChesskingBW.jpg",  
                SlideShowImageFolder = @"C:\Users\Sushil\Pictures",  
                //KI_Email = "******@gmail.com",  
                mail_server = "smtp.gmail.com",  
                Mahindra_Ac = "2-252",  
                BackgroundImage = @"..\..\Resources\chesskingbw.jpg",  
                ServerReportPath = @"http://server/reportserver";  
      
            private int  
                MdiSlideTimer = 10000,  
                s_cashgl = 1,  
                s_debtorgl = 2,  
                s_creditorgl = 3,  
                s_drivergl = 15,  
                CodeGroupInterVal = 25,  
                mail_port = 587,  
                PosDefaultQty = 1;  
      
      
            //Bill To MultiGRn Link at Kimya set it to 2 otheriwse 0,LC Sales, Labour Sales   
            LcSales SaleGrnLinq = LcSales.Not_Applicable;  
            [CategoryAttribute("Sales"), DescriptionAttribute("Labour Charges Work Billing Methods")]  
            public LcSales _SaleGrnLinq  
            {  
                get => SaleGrnLinq;  
                set => SaleGrnLinq = value;  
            }  
            [CategoryAttribute("Sales"), DescriptionAttribute("Verify Production Stock While Billing")]  
            Sales2Production SalesLinkedToProduction = Sales2Production.Not_Applicable;  
            public Sales2Production _SalesLinkedToProduction  
            {  
                get => SalesLinkedToProduction;  
                set => SalesLinkedToProduction = value;  
            }  
      
            [CategoryAttribute("Sales"), DescriptionAttribute("Show Item List Having Order Acceptance Entry")]  
            [TypeConverter(typeof(DyasOfWeekConverter1))]  
            public bool _BillItemsOnOaItems  
            {  
                get => BillItemsOnOaItems;  
                set => BillItemsOnOaItems = value;  
            }  
      
            [CategoryAttribute("Sales"), DescriptionAttribute("Point Of Sale Default Qty.")]  
            public int _PosDefaultQty  
            {  
                get => PosDefaultQty;  
                set => PosDefaultQty = value;  
            }  
      
            [CategoryAttribute("Reports"), DescriptionAttribute("Sql Server Reports Path")]  
            //[Category("Reports")]  
            //[Description("Sql Server Reports Path")]  
            ////[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            ////your poject should refer to System.Design.dll .net 4.0, and using System.Design   
            //[EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            public string _ServerReportPath  
            {  
                get => ServerReportPath;  
                set => ServerReportPath = value;  
            }  
      
            [CategoryAttribute("Ledgers"), DescriptionAttribute("Mahindra A/c. No.")]  
            public string _Mahindra_Ac  
            {  
                get => Mahindra_Ac;  
                set => Mahindra_Ac = value;  
            }  
      
            [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Back Ground Image File")]  
            [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            public string _BackgroundImage  
            {  
                get => BackgroundImage;  
                set => BackgroundImage = value;  
            }  
      
            //[CategoryAttribute("E-Mail"), DescriptionAttribute("Send E-mail From A/c.")]  
            //public string _KI_Email  
            //{  
            //    get =>KI_Email;  
            //    set =>KI_Email=value;  
            //}  
      
            [CategoryAttribute("E-Mail"), DescriptionAttribute("Mail Server Name")]  
            public string _mail_server  
            {  
                get => mail_server;  
                set => mail_server = value;  
            }  
      
            [CategoryAttribute("E-Mail"), DescriptionAttribute("Google Default Port is 587")]  
            public int _mail_port  
            {  
                get => mail_port;  
                set => mail_port = value;  
            }  
      
      
            [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Q.C.Code Each Group Id Gap")]  
            public int _CodeGroupInterVal  
            {  
                get => CodeGroupInterVal;  
                set => CodeGroupInterVal = value;  
            }  
            //https://www.codeproject.com/Articles/6294/Description-Enum-TypeConverter  
            DaysOfWeek WeeklyOff = DaysOfWeek.Sunday;  
            [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Weekly off")]  
            //[TypeConverter(typeof(DyasOfWeekConverter))]  
            public DaysOfWeek _WeeklyOff  
            {  
                get => WeeklyOff;  
                set => WeeklyOff = value;  
            }  
            Period SeePastDataOf = Period.Week;  
            [CategoryAttribute("Bansal ERP"), DescriptionAttribute("Shiow Data Of Past")]  
            //[TypeConverter(typeof(DyasOfWeekConverter))]  
            public Period _SeePastDataOf  
            {  
                get => SeePastDataOf;  
                set => SeePastDataOf = value;  
            }  
            //  
            ImageLayout MdiImageLayout = ImageLayout.Center;  
            [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
            public ImageLayout _MdiImageLayout  
            {  
                get => MdiImageLayout;  
                set => MdiImageLayout = value;  
            }  
      
            [CategoryAttribute("Slide Show"), DescriptionAttribute("Set Show Next Slide in Milliseconds")]  
            public int _MdiSlideTimer  
            {  
                get => MdiSlideTimer;  
                set => MdiSlideTimer = value;  
            }  
      
            [CategoryAttribute("Sales"), DescriptionAttribute("Sales Rate From Grn\nKimaya Engginering")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _SaleRateFromGRN  
            {  
                get => SaleRateFromGRN;  
                set => SaleRateFromGRN = value;  
            }  
      
            [CategoryAttribute("Slide Show"), DescriptionAttribute("set Single Image or Show From Folder")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _MdiFixedImage  
            {  
                get => MdiFixedImage;  
                set => MdiFixedImage = value;  
            }  
      
            [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
            [EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            public string _SlideShowImageFolder  
            {  
                get => SlideShowImageFolder;  
                set => SlideShowImageFolder = value;  
            }  
      
            [CategoryAttribute("Slide Show"), DescriptionAttribute("Show Your Products Images settings")]  
            [EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            public string _MdiImage  
            {  
                get => MdiImage;  
                set => MdiImage = value;  
            }  
      
            [CategoryAttribute("Sales"), DescriptionAttribute("Is Negative Stock allowed ?")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _AllowNegativeStock  
            {  
                get => AllowNegativeStock;  
                set => AllowNegativeStock = value;  
            }  
            [CategoryAttribute("Sales"), DescriptionAttribute("Yes:User Can Changed Bill Date, No:System Date")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _BillDateEditable  
            {  
                get => BillDateEditable;  
                set => BillDateEditable = value;  
            }  
            [CategoryAttribute("GRN"), DescriptionAttribute("Show Q.C. while MAking GRN")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _QcOnGrn  
            {  
                get => QcOnGrn;  
                set => QcOnGrn = value;  
            }  
            [CategoryAttribute("Purchase"), DescriptionAttribute("Check P.O. On Purchase Entry ")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _Purchase_po  
            {  
                get => Purchase_po;  
                set => Purchase_po = value;  
            }  
            [CategoryAttribute("Sales"), DescriptionAttribute("Exclude Time From Bill Date")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _BillDateWithoutTime  
            {  
                get => BillDateWithoutTime;  
                set => BillDateWithoutTime = value;  
            }  
            [CategoryAttribute("Sales"), DescriptionAttribute("Fetch Bag_packet_qty from item master")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _bag_packet_qty  
            {  
                get => bag_packet_qty;  
                set => bag_packet_qty = value;  
            }  
            [CategoryAttribute("Sales"), DescriptionAttribute("Set Packing Details")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _SalePackingDetailes  
            {  
                get => SalePackingDetailes;  
                set => SalePackingDetailes = value;  
            }  
      
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _Purchase_OnGrn  
            {  
                get => Purchase_OnGrn;  
                set => Purchase_OnGrn = value;  
            }  
      
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No: on Entry, Yes: On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _IssueSlip_OnSave  
            {  
                get => IssueSlip_OnSave;  
                set => IssueSlip_OnSave = value;  
            }  
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _OA_OnSave  
            {  
                get => OA_OnSave;  
                set => OA_OnSave = value;  
            }  
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _OC_OnSave  
            {  
                get => OC_OnSave;  
                set => OC_OnSave = value;  
            }  
      
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _GRNno_OnSave  
            {  
                get => GRNno_OnSave;  
                set => GRNno_OnSave = value;  
            }  
      
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _Billno_OnSave  
            {  
                get => Billno_OnSave;  
                set => Billno_OnSave = value;  
            }  
            [CategoryAttribute("Numbering"), DescriptionAttribute("Will Generate Document Number if No:on Entry,Yes:On Save")]  
            [TypeConverter(typeof(YesNoClassConverter))]  
            public bool _pvno_OnSave  
            {  
                get => pvno_OnSave;  
                set => pvno_OnSave = value;  
            }  
      
      
            [Category("Reports")]  
            [Description("Report Folder Path ")]  
            //[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            //your poject should refer to System.Design.dll .net 4.0, and using System.Design   
            [EditorAttribute(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]  
            public string _CommonFilePath  
            {  
                get => CommonFilePath;  
                set => CommonFilePath = value;  
            }  
      
            //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("GSP Name")]  
            //public string _GSPName { get => GSPName; set => GSPName = value; }  
            //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Authentication web URL")]  
            //public string _AuthUrl { get => AuthUrl; set => AuthUrl = value; }  
            //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Base web URL")]  
            //public string _BaseUrl { get => BaseUrl; set => BaseUrl = value; }  
      
            //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("IRN web URL")]  
            //public string _EwbByIRN { get => EwbByIRN; set => EwbByIRN = value; }  
      
            //[CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("Cancell IRN web URL")]  
            //public string _CancelEwbUrl { get => CancelEwbUrl; set => CancelEwbUrl = value; }  
      
            [CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("E-invoice Via GSP User Name")]  
            public string _UserName { get => UserName; set => UserName = value; }  
            [CategoryAttribute("E-Invoice GSP"), DescriptionAttribute("E-invoice Via GSP User Password")]  
            public string _Password { get => Password; set => Password = value; }  
      
            [CategoryAttribute("Ledgers"), DescriptionAttribute("Customer G.L.Id")]  
            public int _s_debtorgl  
            {  
                get => s_debtorgl;  
                set => s_debtorgl = value;  
            }  
            [CategoryAttribute("Ledgers"), DescriptionAttribute("Cash On Hand ID")]  
            public int _s_cashgl  
            {  
                get => s_cashgl;  
                set => s_cashgl = value;  
            }  
            [CategoryAttribute("Ledgers"), DescriptionAttribute("Suppliers G.L.ID")]  
            public int _s_creditorgl  
            {  
                get => s_creditorgl;  
                set => s_creditorgl = value;  
            }  
      
            [CategoryAttribute("Ledgers"), DescriptionAttribute("Drivers G.L.ID")]  
            public int _s_drivergl  
            {  
                get { return s_drivergl; }  
                set { s_drivergl = value; }  
            }  
            //  
            [CategoryAttribute("PDI"), DescriptionAttribute("PDI Auto Fill Key")]  
            public string _PdiIdentityKey  
            {  
                get { return PdiIdentityKey; }  
                set { PdiIdentityKey = value; }  
            }  
      
            public ConfigMgr()  
            {  
                //  
                // TODO: Add constructor logic here  
                //  
            }  
        }  
        class YesNoClassConverter : BooleanConverter  
        {  
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)  
            {  
                return (bool)value ? "Yes" : "No";  
            }  
      
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)  
            {  
                return (string)value == "Yes";  
            }  
      
        }  
      
        public class DyasOfWeekConverter : EnumConverter  
        {  
            private Type _enumType;  
            /// <summary>Initializing instance</summary>  
            /// <param name="type">type Enum</param>  
            ///this is only one function, that you must   
            ///to change. All another functions for enums   
            ///you can use by Ctrl+C/Ctrl+V  
            public DyasOfWeekConverter(Type type) : base(type)  
            {  
                _enumType = type;  
            }  
      
            public override bool CanConvertTo(ITypeDescriptorContext context, Type destType)  
            {  
                return destType == typeof(string);  
            }  
      
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)  
            {  
                FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, value));  
                DescriptionAttribute dna =  
                  (DescriptionAttribute)Attribute.GetCustomAttribute(  
                    fi, typeof(DescriptionAttribute));  
      
                if (dna != null)  
                    return dna.Description;  
                else  
                    return value.ToString();  
            }  
      
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type srcType)  
            {  
                return srcType == typeof(string);  
            }  
      
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)  
            {  
                foreach (FieldInfo fi in _enumType.GetFields())  
                {  
                    DescriptionAttribute dna =  
                      (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));  
      
                    if ((dna != null) && ((string)value == dna.Description))  
                        return Enum.Parse(_enumType, fi.Name);  
                }  
                return Enum.Parse(_enumType, (string)value);  
            }  
        }  
      
        public class DyasOfWeekConverter1 : EnumConverter  
        {  
            /*  
            https://social.msdn.microsoft.com/Forums/vstudio/en-US/c71938b7-aff1-4fcb-aeff-a07457220ec4/how-do-i-display-enumerations-nicer-in-a-property-grid?forum=csharpgeneral  
            */  
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)  
            {  
                return sourceType == typeof(string);  
            }  
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)  
            {  
                return Enum.Parse(typeof(DayOfWeek), value.ToString().ToUpper().Replace(' ', '_'));  
            }  
            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)  
            {  
                return destinationType == typeof(string);  
            }  
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)  
            {  
                string s = value.ToString();  
                int i = s.IndexOf('_');  
                return s[0] + s.Substring(1, i - 1).ToLower() + ' ' + s[i + 1] + s.Substring(i + 2).ToLower();  
            }  
            public DyasOfWeekConverter1() : base(typeof(DayOfWeek)) { }  
        }  
      
          
      
    }][1]  
    
    0 comments No comments

  3. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-04-15T14:28:16.087+00:00

    You need to create the database I provided, build, run the project see it then examine the code.

    Also I highly recommend not using a string column as a primary key, instead a int.

    Your class should be

    using System.ComponentModel;
    
    namespace PropertyGridSqlServer.Classes
    {
        public class AppProperties
        {
            [Browsable(false)]
            public int Id { get; set; }
            public string Name { get; set; }
    
            public string Value { get; set; }
    
            public override string ToString()
            {
                return Name;
            }
        }
    }
    

    Read data

    using System.Collections.Generic;
    using System.Data.SqlClient;
    
    namespace PropertyGridSqlServer.Classes
    {
        public class AppPropertiesOperations
        {
            private static string ConnectionString =
                "Data Source=.\\SQLEXPRESS;Initial Catalog=mfgst;" +
                "Integrated Security=True";
    
            public static List<AppProperties> Read()
            {
                var list = new List<AppProperties>();
                var selectStatement = "SELECT Id, [Name], [Value] FROM dbo.AppProperties;";
    
                using (var cn = new SqlConnection() { ConnectionString = ConnectionString })
                {
                    using (var cmd = new SqlCommand() { Connection = cn, CommandText = selectStatement })
                    {
                        cn.Open();
                        var reader = cmd.ExecuteReader();
    
                        while (reader.Read())
                        {
                            list.Add(new AppProperties()
                            {
                                Id = reader.GetInt32(0),
                                Name = reader.GetString(1),
                                Value = reader.GetString(2)
                            });
                        }
                    }
                }
    
                return list;
            }
        }
    }
    

    Call the above

    AppPropertiesOperations.Read();
    

    Then following what I did for Product code sample.

    Then look at the new code I provided in the GitHub repository which only provides base code, enough for you to take it from here.

    In closing, this is all I have time for, time to get to work.

    Hopefully this gets you going.


  4. Sushil Agarwal 406 Reputation points
    2021-04-15T16:07:52.767+00:00

    Thank you very much mam for your untired effort to help me.

    i beg your parden, i am a new bee and may be wrong to say follwoing but

    what i feel if i take your approach then it will show vanila type each table row , column wise properties , their propertygrid grouping, validating, enum etc will not be seen.

    please have a look at following pic.

    There are some properties were enums

    Thanks a lot again

    88258-propertygrid.png


  5. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-04-16T12:35:33.087+00:00

    Using a DataGridView is not right for that many properties but with a few sure it would work e.g.

    88634-f1.png

    A better way is to data bind properties to single controls e.g. for a yes/no use a CheckBox, for multiple selections a ComboBox etc.

    Simple example which can be done layout wise in various ways and if needed with scrollbars

    88574-f2.png

    A PropertyGrid may not be the best solution.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.