how to get the non english value of a DataTextField and its DataValueField from a dropdownlist in asp.net

300 views Asked by At

I have the following dropdownlist in my project which takes its data from its relevant SqlDataSource. The problem which I am facing with is that the dropdownlist includes non-english items(ProvinceName) and I can get neither the DataTextField value nor the DataValueField value of an item in code behind file.

here is the markup:

<div class="col-lg-6">
    <label for="ddlProvince" class="control-label">Province</label>
    <asp:DropDownList AutoPostBack="true" ID="ddlProvince" 
         DataSourceID="sqlDsProvince" DataTextField="ProvinceName" 
         DataValueField="ProvinceID" CssClass="dropdown form-control" runat="server" />
    <asp:SqlDataSource ID="sqlDsProvince" runat="server" ConnectionString="<%$ connectionStrings:connectionStr %>" SelectCommand="SELECT [ProvinceID], [ProvinceName] FROM [Provinces]" ProviderName="System.Data.SqlClient">
    </asp:SqlDataSource>
</div>

When I run the following statements

testLabel.Text = ddlProvince.SelectedItem.Text;

or

testLabel.Text=ddlProvince.SelectedValue;

I get the NullReferenceException

UPDATE I have another dropdownlist which doesn't include non-english item when I get items of this dropdownlist into testLabel everything works

<asp:DropDownList ID="ddlGraduationClass" CssClass="dropdown form-control" runat="server">
                                <asp:ListItem Text="12" Value="12"></asp:ListItem>
                                <asp:ListItem Text="14" Value="14"></asp:ListItem>
                            </asp:DropDownList>
2

There are 2 answers

0
Tetsuya Yamamoto On BEST ANSWER

The ddlProvince.SelectedItem & ddlProvince.SelectedValue has null value while the dropdownlist options doesn't have any option items during Page_Load event, or data rebinding during postback has occurred (considering AutoPostBack="true", so it can trigger postback). To rebind the data at first time, use IsPostBack check on corresponding event:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlProvince.DataSource = sqlDsProvince;
        ddlProvince.DataTextField = "ProvinceName";
        ddlProvince.DataValueField = "ProvinceID";
        ddlProvince.DataBind(); // don't forget to add this for binding dropdownlist items
    }
}

NB: ddlGraduationClass can also bound for another SqlDataSource in same ways like sample above.

References:

Why is my DropDownList's SelectedItem not working?

C# dropdown selected item null when list of strings/objects bound to the Data source

6
Caius Jard On

In the latter statement, it can really only be that testLabel is null or ddlProvince is null. I don't see testLabel defined in the page code you posted; are you sure it has an instance? If you pause the debugger on these lines of code, you'll be able to see what variable is claimed to be null. It won't be because ddlProvince has a foreign word selected