-->

Object reference not set to an instance of an obje

2019-07-05 03:57发布

问题:

I have a text box and a RadComboBox like this :

<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px" 
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true"></asp:TextBox>
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="Contains" ItemsPerRequest="100"
MarkFirstMatch="true" Width="380px" EnableAutomaticLoadOnDemand="True" EmptyMessage="-emp name-" ShowMoreResultsBox="True" AutoPostBack="True">
</telerik:RadComboBox>

According to the Telerik Documentation

Set a data source to the RadComboBox. Use either DataSourceID or the DataSource property to do this and set the DataTextField and DataValueField properties to the respective fields in the data source. (Note that when using DataSource you must set the property on each postback, most conveniently in Page_Init.) Set EnableAutomaticLoadOnDemand to true.


 protected void BindEmployees()
        {

            rad_ddl_inner_emp_name.Items.Clear();
            rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
            rad_ddl_inner_emp_name.DataTextField = "name";
            rad_ddl_inner_emp_name.DataValueField = "emp_num";
            rad_ddl_inner_emp_name.DataBind();

        }

 protected void Page_Init(object sender, EventArgs e)
        {
            BindEmployees();
        }

 protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
        {
            rad_ddl_inner_emp_name.ClearSelection();
            rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()).Selected = true;//Get exception here Object reference not set to an instance of an object.
        }

I find rad_ddl_inner_emp_name.Items.Count = 0 !! before set the selection ! How to fix this problem ?

回答1:

As I'm sure you aware of by now, the radcombox typeahead functionality searches text via client side interaction and not by value, which is why you can't find the values.

What I would suggest is having a secondary object to search by emp_num (assuming that's the value that will always be entered into the textbox).

For example, create a global variable:

private Dictionary<string, string> Emp_Dict = new Dictionary<string, string>(); 

Then populate this dictionary when you do your binding. The following code assumes an ienumerable type being returned. If not you may have to populate the dictionary differently. Also, for this to work, you have to include (System.Linq).

    var dataSource = Utilities.GetAllEmployees();
    Emp_Dict = dataSource.ToDictionary(ex => ex.emp_num, ex => ex.name);
    rad_ddl_inner_emp_name.Items.Clear();
    rad_ddl_inner_emp_name.DataSource = dataSource;
    rad_ddl_inner_emp_name.DataTextField = "name";
    rad_ddl_inner_emp_name.DataValueField = "emp_num";
    rad_ddl_inner_emp_name.DataBind();

So now we need to use the dictionary on the text changed event.

protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
    rad_ddl_inner_emp_name.ClearSelection();
    if (Emp_Dict.ContainsKey(txt_inner_emp_num.Text.TrimEnd()))
    {
        rad_ddl_inner_emp_name.SelectedValue = txt_inner_emp_num.Text.TrimEnd();
        rad_ddl_inner_emp_name.Text = Emp_Dict[txt_inner_emp_num.Text.TrimEnd()];
    }

}

Now when the text changes in the text box, the radcombobox will update when a valid emp_num is entered into the textbox.



回答2:

The Problem is that the Items only get loaded when you request them!

Set

EnableAutomaticLoadOnDemand="False"

and it will work!

UPDATE:

if you want to use LoadOnDemand set these two Properties and delete the EnableAutomicLoadOnDemand!

EnableLoadOnDemand="True"
EnableItemCaching="True"

UPDATE 2: Enable ItemCaching isn´t necessary, but it doesn´t hurt!



回答3:

You do not need to bind data to RadComboBox on every postback unless you disable the view state.

Filter, MarkFirstMatch and EnableAutomaticLoadOnDemand are not useful in your case as you are loading all employees by yourself.

LoadOnDemand basically is when user starts typing inside ComboBox, ComboBox fires ItemsRequested event and retrieves data via ajax.

<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px" 
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true" />

<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" 
   CausesValidation="False" Culture="ar-EG">
</telerik:RadComboBox>

protected void Page_Init(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
        rad_ddl_inner_emp_name.DataTextField = "name";
        rad_ddl_inner_emp_name.DataValueField = "emp_num";
        rad_ddl_inner_emp_name.DataBind();
    }
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
    string value = txt_inner_emp_num.Text;
    if(!string.IsNullOrWhiteSpace(value))
    {
        value = value.Trim();
        if (rad_ddl_inner_emp_name.Items
            .FindItemByValue(txt_inner_emp_num.Text.Trim()) != null)
            rad_ddl_inner_emp_name.SelectedValue = value;
    }
}


回答4:

Since you don't have any item in rad_ddl_inner_emp_name.Items you can set txt_inner_emp_num.Text as selected in ddl.

First check if rad_ddl_inner_emp_name.Items count > 0 then set desired text selected. Or you can check if rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()) is not null.