[英]Displaying primary key from database in order from least to greatest in C#
In my database the primary keys are in order from least to greatest (1,2,3, etc.) but when I load them into my combobox they are displayed out of order. 在我的数据库中,主键的顺序是从最小到最大(1、2、3等),但是当我将它们加载到组合框中时,它们的显示顺序不正确。 I'm sure there is an easy fix to this, but I'm stuck.
我敢肯定有一个简单的解决办法,但是我被卡住了。
public void fillComboBox()
{
try
{
// query to pull invoice ids
string sql = "SELECT PersonalInfo.[ID] FROM PersonalInfo order by ID";
// adapter to send query to database
OleDbDataAdapter daInvoices = new OleDbDataAdapter(sql, Conn);
// fill dataset
daInvoices.Fill(cusNumDS, "PersonalInfo");
// declare data source for invoice id combo box
custCB.DataSource = cusNumDS.Tables[0];
custCB.DisplayMember = "PersonalInfo";
custCB.ValueMember = "ID";
// bind data source to combo box
custCB.DataBindings.Add("SelectedValue", cusNumDS.Tables[0], "ID");
}
catch (Exception ex)
{
// error message if trouble pulling invoice ids from database
MessageBox.Show("Trouble pulling invoices from database because: " + ex,
"Database Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
SELECT PersonalInfo.[ID] FROM PersonalInfo order by 1 ASC
尝试这个....
From a comment, you say.. 从评论中,你说..
No the combobox displays everything that begins with 1, such as 1, 10, 11, 12...2, 20, 21, 22 etc. I want it to be in order from lowest to highest.
没有组合框显示以1开头的所有内容,例如1、10、11、12 ... 2、20、21、22等。我希望它按从低到高的顺序排列。
This means a Lexicographical Ordering for text is being used during the sorting. 这意味着在排序过程中将使用文本的词典顺序 。 Now, there are two reasons (I can think of) that would cause this.
现在,有两个原因(我能想到)会导致这种情况。
The KEY might be a char/varchar column and the ordering is applied by the database. KEY可能是char / varchar列,并且该顺序由数据库应用。 If this is the case, then the following query should work:
如果是这种情况,则以下查询应该起作用:
SELECT PersonalInfo.[ID] FROM PersonalInfo ORDER BY CAST(id AS INT) -- for MS Access maybe: ORDER BY CInt(id)
And if it does fix the problem then the scheme should probably be fixed! 如果确实解决了问题,则该方案可能应该得到解决!
A sort might be applied after the query, such as within the ComboBox itself! 查询后可能会进行排序,例如在ComboBox本身中! Make sure that Sorted is false.
确保Sorted为false。
[The Sorted] property specifies whether the ComboBox sorts existing entries and add new entries to the appropriate sorted position in the list.
[Sorted]属性指定ComboBox是否对现有条目进行排序并将新条目添加到列表中的适当排序位置。 You can use this property to automatically sort items in a ComboBox .. The sort is case-insensitive and in alphabetically ascending order.
您可以使用此属性来自动对ComboBox中的项目进行排序。排序不区分大小写,并且按字母升序排列。
.. or it could be a combination of both! ..或者可能是两者的组合! Also, make sure that the code being run/tested is the latest version and is really being used.
另外,请确保正在运行/测试的代码是最新版本并且确实在使用中。
SELECT PersonalInfo.[ID] FROM PersonalInfo order by ID ASC
将ASC放在选择语句的末尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.