C# Propertygrid default value typeconverter

cpropertygridwinforms

I have a propertygrid with a dropdown box. In my application a user can click on a block and then the properties of that block are shown in a propertygrid. But the first time they click on a block an invalid value (0) is shown in the dropdown. How can I make sure that a valid value is shown?

Here is some code of the TypeConverter:

public class DynamicFormScreenId : Int32Converter
{

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        Database database = new Database();
        database.StoredProcedureName = "SP naam";

        int[] id = null;
        if (database.ExecuteStoredProcedure())
        {
            int totalIds = database.DataTable.Rows.Count; 
            id = new int[totalIds];

            for (int i = 0; i < totalIds; i++)
            {
                id[i] = Convert.ToInt32(database.DataTable.Rows[i][0]);
            }
        }

        return new StandardValuesCollection(id);
    }

    public override bool GetStandardValuesExclusive(
                       ITypeDescriptorContext context)
    {
        return true;
    }
}

And the property in my class:

[TypeConverter(typeof(DynamicFormScreenId)),
CategoryAttribute("Screen Settings"),
Description("The id of the screen")]
public int ScreenId
{
    get { return _screenId; }
    set { _screenId = value; }
}

SOLUTION

I set the default value of ScreenId in the constructor:

private void Constructor(string name)
{
    _controlName = name;

    // Set screenId default value
    Database database = new Database("connectionstring");
    database.StoredProcedureName = "mySP";

    if (database.ExecuteStoredProcedure())
    {
        if (database.DataTable.Rows.Count > 0)
        {
            _screenId = Convert.ToInt32(database.DataTable.Rows[0]["id"]);
        }
    }
}

Best Answer

Have you tried the DefaultValueAttribute in System.ComponentModel?

From MSDN:

You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value.

private bool myVal=false;

[DefaultValue(false)]
 public bool MyProperty {
    get {
       return myVal;
    }
    set {
       myVal=value;
    }
 }
Related Topic