V. Benavides V. Benavides - 3 months ago 10
SQL Question

Error when setting ComboBox.Sorted property to true

It is a basic

ComboBox
with the following code:

private void hotel_Selection()
{
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("SELECT * FROM HOTEL WHERE HOTEL_CITY = @CITY", con);
cmd.Parameters.AddWithValue("@CITY", citiesID);
SqlDataReader dr1;
dr1 = cmd.ExecuteReader();
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(int));
dt1.Columns.Add("NAME", typeof(string));
dt1.Load(dr1);
hotelCbox.ValueMember = "ID";
hotelCbox.DisplayMember = "NAME";
hotelCbox.DataSource = dt1;
hotelCbox.SelectedIndex = -1;
con.Close();
}


The problem arises when I try to get the
ComboBox
to be sorted from A-Z. If I don't set the sorted property to true it works, but as soon as I try to set the property to true it gives me the error for the
System.Data.DataRowView
and it is slowly driving me crazy.Any idea what am I doing wrong, perhaps as it is sql or am I missing something along the way.

Answer

As mentioned in documentations for Sorted property:

Attempting to set the Sorted property on a data-bound control raises an ArgumentException. You must sort the data using the underlying data model.

To solve the problem you can sort the DataTable by assigning a sort expression to the Sort property of its DefaultView.

The value of property can be the column name followed by ASC for ascending sort or DESC for descending sort. Columns are sorted ascending by default. You can apply sort to multiple columns by separating sort expressions by comma.

dt1.DefaultView.Sort = "Name";

You also can sort your query by adding an ORDER BY:

SELECT * FROM HOTEL WHERE HOTEL_CITY = @CITY ORDER BY Name
Comments