ASP.NET上的FindByValue DropDownList [英] FindByValue on ASP.NET DropDownList

查看:140
本文介绍了ASP.NET上的FindByValue DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在包含名为ddlAggerationUnitId的DropDownList的自定义用户控件中具有以下代码。 DropDownList在Page_Load()事件上是DataBind'd。 值设置为40,存在。如果我删除set方法的逻辑页面将加载并选择正确的项目,但如果该值是伪造的,页面将抛出异常。我想通过查看值是否存在,然后尝试设置它,因此为什么逻辑是必要的。

I have the following code in a custom user control that contains a DropDownList named ddlAggerationUnitId. The DropDownList is DataBind'd on the Page_Load() event. The "value" is set to be 40 and it DOES exist. If I remove the logic for the set method the page will load and select the correct item, but if the value is bogus the page throws an exception. I'd like to avoid that exception by seeing if the value exists BEFORE trying to set it, hence why the logic is necessary.

现在看起来像编译器将if语句评估为false,即使我知道一个事实也是如此。

Right now it looks like the compiler is evaluating the if statement as false, even though I know for a fact it should be true.

public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        if (ddlAggerationUnitId.Items.FindByValue(value.ToString()) != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}

任何帮助将不胜感激!谢谢!

Any help would be greatly appreciated! Thanks!

编辑:这是我的Page_Load()事件:

Here is my Page_Load() event:

protected void Page_Load(object sender, EventArgs e)
{
    ddlAggerationUnitId.DataSource = ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}


推荐答案

不过我认为DataBind有两倍的奇怪。这证实了我以前怀疑数据绑定在FindByValue()之后?

The following code currently works, however I think it's a bit strange to DataBind twice. This confirms my earlier suspicion that the data was being binded AFTER FindByValue()?

任何人都有任何关于如何清理此代码的想法?

Anyone have any ideas on how to clean this code up?

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindDdlAggerationUnitId();
    }
}

private void BindDdlAggerationUnitId()
{
    ddlAggerationUnitId.DataSource = SIGOpsGUI.App_Code.Business.ExternalAccount.GetAggregationUnits();
    ddlAggerationUnitId.DataTextField = "Value";
    ddlAggerationUnitId.DataValueField = "Key";
    ddlAggerationUnitId.DataBind();
}


public long? Value
{
    get { return Int64.Parse(ddlAggerationUnitId.SelectedItem.Value); }
    set
    {
        BindDdlAggerationUnitId();
        ddlAggerationUnitId.SelectedIndex = -1;
        ListItem item = ddlAggerationUnitId.Items.FindByValue(value.ToString());
        if (item != null)
        {
            ddlAggerationUnitId.SelectedValue = value.ToString();
        }
    }
}

这篇关于ASP.NET上的FindByValue DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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