简体   繁体   English

System.ArgumentException:“设置 DataSource 属性时无法修改项目集合。” C# Windows Forms

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

So I'm trying to take combobox and textbox input values from the current form and add them to a listbox on the following form.所以我试图从当前表单中获取 combobox 和文本框输入值,并将它们添加到以下表单的列表框中。 However I get the following error但是我收到以下错误

System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.' System.ArgumentException:“设置 DataSource 属性时无法修改项目集合。”

I've tried to make the datasource = null 'listbox1.DataSource = null;'我试图使数据源 = null 'listbox1.DataSource = null;' and clear the listbox contents 'listbox1.Items.Clear();'.并清除列表框内容“listbox1.Items.Clear();”。 However, when I proceed to the next form the to see the saved values, the values are invisible in the listbox.但是,当我进入下一个表单以查看保存的值时,这些值在列表框中是不可见的。 However, all of the inputs are saved to the sql database.但是,所有输入都保存到 sql 数据库中。

Modified Method修改方法

Output Output

Any help would be highly appreciated.任何帮助将不胜感激。

Code Block related to the issue与问题相关的代码块

@aepot I have followed your code example and still seem to get the empty listbox. @aepot 我遵循了您的代码示例,但似乎仍然得到空列表框。 Also, if I use AccountInfo which is my property class instead of string then the exception from before comes back.此外,如果我使用 AccountInfo ,这是我的财产 class 而不是字符串,那么之前的异常就会回来。 I'm not sure what else can be done at this point.我不确定此时还能做些什么。 AccountInfo Class Adjusting Comparisson Result Outcome AccountInfo Class调整比较结果结果

@aepot Here is the code if you're still interested in helping DataAccess Class @aepot 如果您仍然对帮助 DataAccess 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);
            }
                 
        }

Here I'm just binding variables to input fields这里我只是将变量绑定到输入字段

  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 = "";

Here I'm trying to retrieve info from the previous form在这里,我正在尝试从以前的表单中检索信息

 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();
        }

Try BindingList<T> as DataSource尝试BindingList<T>作为DataSource

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

Then assign the DataSource然后分配DataSource

listBox1.DataSource = items;

Then you can modify the Collection fluently然后就可以流畅地修改Collection了

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

or或者

items.Clear();

ListBox will update its layout automatically. ListBox将自动更新其布局。

Note: if you'll reassign new BindingList instance to items during the app execution, don't forget to reassign the DataSource then.注意:如果您在应用程序执行期间将new BindingList实例重新分配给items ,请不要忘记重新分配DataSource

The same can be applied to any Control which has DataSource .这同样适用于任何具有DataSourceControl


Edit编辑

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但是,现在当我输入要在 listbox1 中显示的值时,列表框是空白的,但您可以看到列表框中应出现文本的每一行的蓝色选定字段

Cannot reproduce that.无法重现。 See the following code.请参阅以下代码。 To reproduce it in Designer I've just added a ListBox and a Button without any additional setup.为了在 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");
    }
}

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.ArgumentException:设置DataSource属性时,不能修改Items集合 - System.ArgumentException: Items collection cannot be modified when the DataSource property is set 设置DataSource属性后,将无法修改项目集合。 C# - Items collection cannot be modified when the DataSource property is set. c# 在c#中设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set in c# 设置DataSource属性时,无法修改c#项目集合 - c# Items collection cannot be modified when the DataSource property is set 在C#Windows中设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set in C# Windows C#ListBox:设置DataSource属性时,无法修改Items集合 - C# ListBox : Items collection cannot be modified when the DataSource property is set 列表框错误:设置了DataSource属性时,无法修改项目集合 - listbox error: Items collection cannot be modified when the DataSource property is set 例外:设置DataSource属性时,无法修改项集合 - Exception : Items collection cannot be modified when the DataSource property is set 设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set 如何在不同的 colors 中为列表框中的项目着色? 出现异常:设置 DataSource 属性后无法修改 Items 集合 - How to color items in listBox in different colors? getting exception : Items collection cannot be modified when the DataSource property is set
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM