在ASP.Net中的下拉列表中动态填充和设置值

时间:2012-07-03 11:02:08

标签: c# asp.net

我有一个表格,我有4个下拉菜单国家,州,区和市。在表单加载时填充国家/地区,并在选定的索引更改事件上填充休息。序列是On Country选定的索引已更改状态。在州 - >人口稠密的地区和地区 - >城市人口稠密。

为了保存它工作正常,但当我更新值时,它显示空引用错误。在我得到的调试中,下拉列表没有填充,而我正在尝试设置值。以下是我的代码。

using (var manager = new LocationManager())
        {
            var dt = manager.GetLocationById(i);
            if (dt.Rows.Count == 1)
            {
                Countries.SelectedValue = Countries.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value;
                BindStates(Convert.ToInt32(Countries.SelectedItem.Value));

                States.SelectedValue = States.Items.FindByText(dt.Rows[0]["State"].ToString()).Value;
                BindDistricts(Convert.ToInt32(States.SelectedItem.Value));

                Districts.SelectedValue = Districts.Items.FindByText(dt.Rows[0]["District"].ToString()).Value;
               BindCities(Convert.ToInt32(Districts.SelectedItem.Value));

                Cities.SelectedValue = Cities.Items.FindByText(dt.Rows[0]["City"].ToString()).Value;
                Pincode.Text = dt.Rows[0]["Pincode"].ToString();

                ViewState["Id"] = dt.Rows[0]["LocationId"].ToString();



            }
        }

我收到错误:{“对象引用未设置为对象的实例。”}在方法

  

BindStates(Convert.ToInt32(Countries.SelectedItem.Value));

3 个答案:

答案 0 :(得分:0)

检查Countries.SelectedItem!= null

答案 1 :(得分:0)

@Amit Ranjan:绑定页面init方法中的所有值,并在页面加载时为所有下拉列表选择特定值:

您将获得空引用,因为没有值已经绑定到下拉列表。

在页面init将所有值绑定到下拉列表          印度     我们     联合王国 ASP:DropDownList的>

页面加载

DropDownList .SelectedValue= dt.Rows[0]["Country"].ToString()).Value;

答案 2 :(得分:0)

我认为问题不在于人口下降,而是在找到价值时,

Countries.Items.FindByText(dt.Rows[0]["Country"].ToString())

找不到任何匹配值,它将返回null。因此在null上应用'Value'属性会产生错误。

你可以在选择之前进行空检查。 如下所示:

countryDropDown.SelectedValue = countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()) != null ? countryDropDown.Items.FindByText(dt.Rows[0]["Country"].ToString()).Value : countryDropDown.Items.FindByText("-Please select-").Value;
相关问题