gpt4 book ai didi

C# 为什么不能设置动态创建的组合框的 selectedValue?

转载 作者:太空狗 更新时间:2023-10-30 00:03:59 27 4
gpt4 key购买 nike

我在类中创建了一个组合框,并想为该组合框设置选定值。但是当我这样做时,selectedValue 保持为空,当我尝试设置 selectedIndex 时,我得到一个 ArgumentOutOfRangeException。

代码:

public Control GenerateList(Question question)
{
// Clear the local givenAnswer collection
_givenAnswer.Clear();

// Get a list with answer possibilities
List<QuestionAnswer> answers = question.GetAnswerSort();

// Get a collection of given answers
Collection<QuestionnaireAnswer> givenAnswers = question.GetGivenAnswers();

_givenAnswer = givenAnswers;

ComboBox cmb = new ComboBox();
cmb.Name = "cmb";
cmb.DisplayMember = "Answer";
cmb.ValueMember = "Id";
cmb.DataSource = answers;
cmb.Dock = DockStyle.Top;

// Check an answer is given to the question
if (givenAnswers != null && givenAnswers.Count > 0)
{
cmb.Tag = givenAnswers[0].AnswerId;
cmb.SelectedValue = givenAnswers[0].AnswerId; // answerId = 55, but SelectedValue stays null
}

cmb.SelectedIndex = 1; // For testting. This will throw a ArgumentOutOfRangeException
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);

return cmb;
}

我希望有人能向我解释发生了什么,这样我就能理解为什么它不起作用。

这是一个完整的小程序,可以说明我的问题。如您所见,它没有设置 SelectedValue,它保持为空

namespace Dynamic_Create_Combo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

GenerateControls gc = new GenerateControls();
Control c = gc.GenerateCombo();

this.SuspendLayout();
this.Controls.Add(c);
this.ResumeLayout(true);
}
}

public class GenerateControls
{
public Control GenerateCombo()
{
// Create datasource
Collection<Car> cars = new Collection<Car>();
Car c = new Car();
c.Id = 1;
c.Name = "Car one";
cars.Add(c);

Car c1 = new Car();
c1.Id = 2;
c1.Name = "Car two";
cars.Add(c1);

Car c2 = new Car();
c2.Id = 2;
c2.Name = "Car three";
cars.Add(c2);

ComboBox cmb = new ComboBox();
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DataSource = cars;
cmb.DisplayMember = "Name";
cmb.ValueMember = "Id";

cmb.SelectedValue = 2;

return cmb;
}
}

public class Car
{
private int _id;
private string _name;

public int Id
{
get { return _id; }
set { _id = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}
}
}

最佳答案

您已将值成员设置为“Id”,但您正在尝试使用“AnswerId”作为所选值。

没有更多细节,很难说为什么设置 SelectedIndex 会抛出 ArgumentOutOfRangeException - 也许组合框会忽​​略所有没有“Id”属性的值, 因此没有给你任何值,所以选择索引 1 是不可能的?

编辑:好的,看起来它只是在可见时才实际进行绑定(bind) - 或者在过程的某个阶段。我已经尝试了一些方法来加速这个过程,但它们似乎没有帮助。您可以做的是推迟您的选择:

EventHandler visibleChangedHandler = null;
visibleChangedHandler = delegate {
cmb.SelectedIndex = 2;
cmb.VisibleChanged -= visibleChangedHandler; // Only do this once!
};
cmb.VisibleChanged += visibleChangedHandler;

这是一个丑陋的解决方法,但它至少应该可以帮助您暂时开始。

关于C# 为什么不能设置动态创建的组合框的 selectedValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3201340/

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