C# Propertygrid 默认值类型转换器 [英] C# Propertygrid default value typeconverter

查看:47
本文介绍了C# Propertygrid 默认值类型转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有下拉框的属性网格.在我的应用程序中,用户可以单击一个块,然后该块的属性显示在属性网格中.但是当他们第一次点击一个块时,下拉列表中会显示一个无效值 (0).如何确保显示有效值?

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?

这是TypeConverter的一些代码:

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;
    }
}

还有我班上的财产:

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

解决方案

我在构造函数中设置了 ScreenId 的默认值:

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"]);
        }
    }
}

推荐答案

您是否尝试过 DefaultValueAttribute 在 System.ComponentModel 中?

Have you tried the DefaultValueAttribute in System.ComponentModel?

来自 MSDN:

您可以创建一个 DefaultValueAttribute具有任何价值.会员默认value 通常是它的初始值.视觉设计师可以使用默认的value 以重置成员的值.

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;
    }
 }

这篇关于C# Propertygrid 默认值类型转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆