gpt4 book ai didi

c# - 组合框索引和非连续索引值

转载 作者:行者123 更新时间:2023-11-29 13:01:05 24 4
gpt4 key购买 nike

不确定如何解释这种情况,但事情是这样的

我正在从数据库中获取 (INT)category_id(VARCHAR)categories_code 并尝试使用 Index(category_id) 将数据推送到 Combobox 内和值(categories_code)。现在,当数据库没有连续数字索引时,我的问题就开始了。 0,1,3 并抛出异常

InvalidArgument=Value of '3' is not valid for 'index'.
Parameter name: index

我的代码是这样的

String query = "SELECT * FROM `category`";
productCategory.Items.Insert(0, "--- SELECT ---");
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(id, name);
}
}
}

对此的预期解决方案是什么?

最佳答案

使用计数器代替?

int i = 1;
using (MySqlDataReader mysqlData = con.Select(query))
{
if (mysqlData.HasRows)
{
while (mysqlData.Read())
{
int id = mysqlData.GetInt32("category_id");
String name = mysqlData.GetString("category_code");
productCategory.Items.Insert(i++, name);
}
}
}

或者你为什么不直接使用 Add方法?

 productCategory.Items.Add(name);

如果你想获取所选项目的类别ID,那么你应该使用一个类。创建一个具有两个属性的类,CategoryIdCategoryCode 。然后有一个List<YourClass>填充它,设置 DataSource , ValueMemberDisplayMember组合框的属性。

productCategory.DataSource = yourList;
productCategory.DisplayMember = "CategoryCode";
productCategory.ValueMember = "CategoryId";

关于c# - 组合框索引和非连续索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com