【问题标题】:Load a specific row as default item in combobox将特定行加载为组合框中的默认项
【发布时间】:2015-12-22 08:08:27
【问题描述】:

我用来自数据库 Access 的数据填充组合框,但我的问题是如何将数据库中的特定行填充为使用 C# 组合框中的默认项?

gerant remplirlistgerant = new gerant();
foreach (gerant ligne in remplirlistgerant.getinfogerant())
{
   cmbgerant.Items.Add(ligne.CIN_GERANT + " - " + ligne.NOM_GERANT + " - " + ligne.PRENOM_GERANT);
}

【问题讨论】:

  • 设置 cmbgerant.SelectedItem = {您的特定项目}
  • 它不起作用,因为在数据库访问中,填充从最后一行开始,如果我选择第 4 行作为默认项目并且它包含例如这一行“4-abcd”,在添加其他行之后如果将其他行作为默认项。例如“8-klmn”......等等?
  • 你应该在填充整个组合框后设置选定的项目。在foreach期间预先保存,然后在foreach之后选择。
  • 但是组合框是空的,它是从数据库中填充的,我该怎么做呢?

标签: c# ms-access combobox


【解决方案1】:

希望我知道你的,

例如if ligne.CIN_GERANT = "aaa" 当前行将被选中。

    gerant remplirlistgerant = new gerant();
    foreach (gerant ligne in remplirlistgerant.getinfogerant())
    {
       cmbgerant.Items.Add(ligne.CIN_GERANT + " - " + ligne.NOM_GERANT + " - " + ligne.PRENOM_GERANT);
       // Example if ligne.CIN_GERANT = "aaa" then select this row.
       if (ligne.CIN_GERANT == "aaa"  )
       {
            cmbgerant.SelectedIndex = cmbgerant.Items.Count - 1;// Item just added
       } 
    }

【讨论】:

  • 谢谢,这是个好主意,但我不明白你为什么设置 -1?
  • 因为索引从 0 到 Items.Count - 1。例如,如果您添加了两行,则要选择第 2 行,第 2 行的索引为 1。
猜你喜欢
  • 2011-03-30
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 2011-03-02
相关资源
最近更新 更多