System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.' C# Windows 表单

System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.' C# Windows Forms

所以我试图从当前表单中获取组合框和文本框输入值,并将它们添加到以下表单的列表框中。但是我收到以下错误

System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.'

我已尝试使数据源 = null 'listbox1.DataSource = null;' 并清除列表框内容 'listbox1.Items.Clear();'。但是,当我继续下一个表单以查看保存的值时,这些值在列表框中是不可见的。但是,所有输入都保存到 sql 数据库中。

Modified Method

Output

非常感谢任何帮助。

Code Block related to the issue

@aepot 我已经按照您的代码示例进行操作,但似乎仍然得到空列表框。另外,如果我使用我的 属性 class 而不是字符串的 AccountInfo,那么之前的异常就会返回。我不确定此时还能做些什么。 AccountInfo Class 调整中 Comparisson 结果 Outcome

@aepot 如果您仍然有兴趣提供帮助,这是代码 数据访问 Class

public void InsertNewCardDetails(string card_Type, string card_Number, string expiry_date, string _ccv, string _duration)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\nauri\source\repos\StylistsApp\Database\UserAccountDatabase.mdf;Integrated Security=True;Connect Timeout=30"))
            {
                List<AccountInfo> accounts = new List<AccountInfo>();
                accounts.Add(new AccountInfo {cardType = card_Type, cardNumber = card_Number, expiryDate = expiry_date, ccv = _ccv, duration = _duration });
                connection.Execute("INSERT INTO[Table] (cardType, cardNumber, expiryDate, ccv, duration) VALUES(@cardType, @cardNumber, @expiryDate, @ccv, @duration)", accounts);
            }
                 
        }

这里我只是将变量绑定到输入字段

  public partial class CardDetails : Form
    {
        public CardDetails()
        {
            InitializeComponent();
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            DataAccess db = new DataAccess();
            SetValueForCardType = comboBox1.SelectedItem.ToString(); 
            SetValueForCardNumber = textBox5.Text;
            SetValueForExpiryDate = textBox2.Text;
            SetValueForCCV = textBox3.Text;
            SetValueForDuration = comboBox2.SelectedItem.ToString();
            db.InsertNewCardDetails(comboBox1.SelectedItem.ToString(), textBox5.Text, textBox2.Text, textBox3.Text, comboBox2.SelectedItem.ToString());
            //MessageBox.Show("Account Created Successfully!");

            this.Close();
            Summary summary = new Summary();
            summary.Show();

        }
    

    
        public static string SetValueForCardType = "";
        public static string SetValueForCardNumber = "";
        public static string SetValueForExpiryDate = "";
        public static string SetValueForCCV = "";
        public static string SetValueForDuration = "";

我在这里尝试从以前的表格中检索信息

 public partial class Summary : Form
    {
        //List<AccountInfo> people = new List<AccountInfo>();
        private BindingList<string> items = new BindingList<string>();
        public Summary()
        {
            InitializeComponent();
        }
        private void Summary_Load(object sender, EventArgs e)
        {

            listBox1.DataSource = items;
        }
        private void button4_Click(object sender, EventArgs e)
        {

            SqlConnection sql = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\nauri\source\repos\StylistsApp\Database\UserAccountDatabase.mdf;Integrated Security=True;Connect Timeout=30");
            sql.Open();                                      
            SqlCommand sqa = new SqlCommand("Select cardType, cardNumber, expiryDate, ccv, duration from [Table] where email =@email", sql);
            sqa.Parameters.AddWithValue("@email", Form1.SetValueForText1);
            SqlDataReader da = sqa.ExecuteReader();
            while (da.Read())
            {
                items.Add("Hello");
                items.Add("World");
                items.Add(da.GetValue(2).ToString());
                items.Add(da.GetValue(3).ToString());
                items.Add(da.GetValue(4).ToString());

            }
            sql.Close();
        }

尝试 BindingList<T> 作为 DataSource

private BindingList<string> items = new BindingList<string>();

然后赋值给DataSource

listBox1.DataSource = items;

然后就可以流畅的修改Collection了

items.Add("Hello");
items.Add("World");

items.Clear();

ListBox 将自动更新其布局。

注意:如果您在应用程序执行期间将 new BindingList 实例重新分配给 items,请不要忘记重新分配 DataSource

这同样适用于具有 DataSource.

的任何 Control

编辑

however, now when I enter the values to be displayed in listbox1, the listbox is blank but you can see the blue selected fields for each line in the listbox where text should appear

无法重现。请参见以下代码。为了在 Designer 中重现它,我只添加了一个 ListBox 和一个 Button,没有任何额外的设置。

public partial class Form1 : Form
{
    private BindingList<string> items = new BindingList<string>();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.DataSource = items;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        items.Add("Hello");
        items.Add("World");
    }
}