milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home

Creating custom control for Windows forms

Details
Written by: Stanko Milosev
Category: Windows Forms
Published: 01 September 2022
Last Updated: 02 September 2022
Hits: 1473
On example is also here


First part:
1. Start new class library for .NET Framework (not core)
2. Name it MyControls.
3. Rename Class1 to MyButton.
4. Reference System.Windows.Forms in my case it was like: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Windows.Forms.dll
5. MyButton inherit from Button.
6. Add property like:
public string MyProperty { get; set; }
7. Create new App Windows forms for .NET Framework (not core)
8. Add new tab in toolbox
9. Drag and drop MyControls.dll

---

Second part - smart tag:

10. Add attribute [Designer(typeof(MyButtonDesigner))]:

using System.ComponentModel;
using System.Windows.Forms;

namespace MyControls
{
    [Designer(typeof(MyButtonDesigner))]
    public class MyButton: Button
    {
        public string MyProperty { get; set; }
    }
}
11. Add class MyButtonDesigner
12. Add reference to System.Design C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.Design.dll in usings add System.Windows.Forms.
13. Add class MyButtonDesigner and inherit from ControlDesigner:
using System.ComponentModel.Design;
using System.Windows.Forms.Design;

namespace MyControls
{
    public class MyButtonDesigner: ControlDesigner
    {
        private DesignerActionListCollection _myButtonActionLists;

        public override DesignerActionListCollection ActionLists
        {
            get
            {
                if (_myButtonActionLists is null)
                {
                    _myButtonActionLists = new DesignerActionListCollection
                    {
                        new MyButtonActionList(Component)
                    };
                }
                return _myButtonActionLists;
            }
        }
    }
}
14. Add class MyButtonActionList, inherit from DesignerActionList:
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;

namespace MyControls
{
    public class MyButtonActionList: DesignerActionList
    {
        private readonly MyButton _myButton;
        private readonly DesignerActionUIService _designerActionUiSvc = null;

        public MyButtonActionList(IComponent component) : base(component)
        {
            _myButton = component as MyButton;
            _designerActionUiSvc =
                GetService(typeof(DesignerActionUIService))
                    as DesignerActionUIService;
        }

        public string MyProperty
        {
            get => _myButton.MyProperty;
            set
            {
                GetPropertyByName("MyProperty").SetValue(_myButton, value);

                _designerActionUiSvc.Refresh(Component);
            }
        }

        public override DesignerActionItemCollection GetSortedActionItems()
        {
            DesignerActionItemCollection items = new DesignerActionItemCollection();

            items.Add(new DesignerActionHeaderItem("My Smart tag"));

            items.Add(new DesignerActionPropertyItem("MyProperty", "MyProperty"));

            return items;
        }

        private PropertyDescriptor GetPropertyByName(string propName)
        {
            var prop = TypeDescriptor.GetProperties(_myButton)[propName];
            if (null == prop)
                throw new ArgumentException(
                    "Matching MyProperty property not found!",
                    propName);
            return prop;
        }
    }
}

Example until now download from here.

---

Third part - UIEditor:

15. In MyButton change MyProperty to:

public MyPropertyType MyProperty { get; set; }

16. Add new class MyPropertyType, decorate with Editor and TypeConverter:

using System.ComponentModel;
using System.Drawing.Design;

namespace MyControls
{

    [Editor(typeof(MyButtonEditor), typeof(UITypeEditor))]
    [TypeConverter(typeof(MyPropertyTypeConverter))]
    public class MyPropertyType
    {
        public string AnotherMyProperty { get; set; }

        public MyPropertyType(string test)
        {
            AnotherMyProperty = test;
        }
    }
}
17. Add one more class MyPropertyTypeConverter:
using System;
using System.ComponentModel;
using System.Globalization;

namespace MyControls
{
        public class MyPropertyTypeConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return true;
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return true;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is null)
            {
                return string.Empty;
            }
            return new MyPropertyType(value.ToString());
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
			return ((MyPropertyType)value)?.AnotherMyProperty;
        }
    }
}
18. Again add class MyButtonEditor:
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace MyControls
{
    public class MyButtonEditor: UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
            => UITypeEditorEditStyle.Modal;

        public override object EditValue(ITypeDescriptorContext context,
            IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            Form myForm = new Form();
            svc?.ShowDialog(myForm);

            return new MyPropertyType("test");
        }
    }
}
Example download from here.

Read dataset's XML and display all contained tables

Details
Written by: Stanko Milosev
Category: Windows Forms
Published: 12 January 2022
Last Updated: 12 January 2022
Hits: 1733
I have saved an XML with DataSet.WriteXml, then I wanted to display values of that XML in a DataGridView, where each DataTable contained in that XML will create new DataGridView. Here I already gave one example of DataTables. Here is code:
DataSet ds = new DataSet();
ds.ReadXml(@"test.xml");

foreach (DataTable dataTable in ds.Tables)
{
	DataGridView dataGridView = new DataGridView();
	dataGridView.Dock = DockStyle.Top;
	dataGridView.DataSource = dataTable;

	dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
	dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
	dataGridView.AllowUserToOrderColumns = true;
	dataGridView.AllowUserToResizeColumns = true;

	Controls.Add(dataGridView);

	Label label = new Label();
	label.Text = dataTable.TableName;
	label.Dock = DockStyle.Top;
	Controls.Add(label);
}
Example download from here without XML attached.

Read dataset's XML and display all contained tables

Details
Written by: Stanko Milosev
Category: Windows Forms
Published: 12 January 2022
Last Updated: 12 January 2022
Hits: 1649
I have saved an XML with DataSet.WriteXml, then I wanted to display values of that XML in a DataGridView, where each DataTable contained in that XML will create new DataGridView:
DataSet ds = new DataSet();
ds.ReadXml(@"test.xml");

foreach (DataTable dataTable in ds.Tables)
{
	DataGridView dataGridView = new DataGridView();
	dataGridView.Dock = DockStyle.Top;
	dataGridView.DataSource = dataTable;

	dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
	dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
	dataGridView.AllowUserToOrderColumns = true;
	dataGridView.AllowUserToResizeColumns = true;

	Controls.Add(dataGridView);

	Label label = new Label();
	label.Text = dataTable.TableName;
	label.Dock = DockStyle.Top;
	Controls.Add(label);
}

Grid, DataSet, BindingSource and TableAdapter another example

Details
Written by: Stanko Milosev
Category: Windows Forms
Published: 08 May 2021
Last Updated: 08 May 2021
Hits: 2150
Another example of DataGridView this time with run-time DataSource binding:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace GridDataSetBindingSourceAndTableAdapterDynamicExample
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      string connectionString =
        "data source=localhost;initial catalog=TestCompleteTest;persist security info=True;Integrated Security=SSPI";

      using (SqlConnection conn = new SqlConnection(connectionString))
      {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Names", conn))
        {
          conn.Open();
          DataSet ds = new DataSet();
          SqlDataAdapter da = new SqlDataAdapter
          {
            SelectCommand = cmd
          };
          da.Fill(ds);
          dataGridView1.DataSource = ds.Tables[0];
        }
      }
    }
  }
}

Taken from here

Example download from here

  1. Grid, DataSet, BindingSource and TableAdapter example
  2. Add items to UltraGrid
  3. Image opacity
  4. Inheriting Windows Forms with Visual C# .NET

Subcategories

C#

Azure

ASP.NET

JavaScript

Software Development Philosophy

MS SQL

IBM WebSphere MQ

MySQL

Joomla

Delphi

PHP

Windows

Life

Lazarus

Downloads

Android

CSS

Chrome

HTML

Linux

Eclipse

Page 38 of 168

  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42