Reputation: 517
How to select value in combobox according to SQLDataReader value.
ASP code:
<asp:SqlDataSource ID="PREFERENCE_DS" runat="server"
ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionStringTEST %>"
SelectCommand="SELECT [ID], [NAME] FROM [OBJECTS] WHERE ([CLASSID] = @CLASSID) UNION ALL SELECT NULL, ' Нет'">
<SelectParameters>
<asp:Parameter DefaultValue="3" Name="CLASSID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<dx:ASPxComboBox ID="PREFERENCE" runat="server" SelectedIndex="0" Width="430px"
ClientInstanceName="preference" AutoPostBack="True"
DataSourceID="PREFERENCE_DS" TextField="NAME" TextFormatString="{0}"
ValueField="ID">
<Columns>
<dx:ListBoxColumn FieldName="ID" Visible="False" />
<dx:ListBoxColumn Caption="Преференция" FieldName="NAME" />
</Columns>
</dx:ASPxComboBox>
I try
PREFERENCE.Value = reader["PREFERENCE"];
and
if (reader["PREFERENCE"] != null)
PREFERENCE.Text = reader["PREFERENCE"].ToString();
else
PREFERENCE.SelectedIndex = PREFERENCE.Items.FindByValue(DBNull.Value).Index;
but it doesn't work.
Upvotes: 1
Views: 2606
Reputation: 641
Based on your code I think I see what you are trying to do here. Your select statement is going to return a null on the union, so I am assuming you want to select that. I set up a test project and do the selection on the Databound event and this seems to work fine. You'll need to go to the properties of your combobox control and set an event for DataBound. Use the following code:
protected void PREFERENCE_DataBound(object sender, EventArgs e)
{
for (int i = 0; i < PREFERENCE.Items.Count; i++)
{
if (PREFERENCE.Items[i].GetValue("ID") == DBNull.Value)
PREFERENCE.Items[i].Selected = true;
}
}
I chose ID here as the field to check for a null, but you could use name, or any other field you want.
Upvotes: 2