【问题标题】:I Cannot bind to the property or column itemDescription on the DataSource我无法绑定到数据源上的属性或列 itemDescription
【发布时间】:2021-04-09 23:30:54
【问题描述】:

当我按下登录名并调用 LoginClick() 方法时,发生异常,这是在我使用 SSMS 将 SQL 数据库中的列名从“itemDescription”更改为“itemName”之后发生的,希望您能帮助我。我已经尝试了一切,并确保我在问这个问题之前进行了研究。我现在被困在这里几个小时了。不知道问题出在哪里。

LoginForm.cs

private void LoginClick()
    {
        if (MTBoxUsername.Text.Length == 0 || MTBoxPassword.Text.Length == 0)
        {
            MessageBox.Show("Please enter your username and password", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
            if (!int.TryParse(MTBoxUsername.Text, out int j))
            {
                MessageBox.Show("Your username is your student number", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            string username = MTBoxUsername.Text;
            string password = MTBoxPassword.Text;
            var student = (from s in DatabaseHelper.db.tblUsers
                           where s.username == long.Parse(username)
                           select s).First();
            if (student != null)
            {
                if (BCrypt.CheckPassword(password, student.password))
                {
                    MessageBox.Show("Login Succesful!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Hide();
                    if (student.userType.Equals("STUDENT"))
                    {
                        var loginStudent = (from s in DatabaseHelper.db.tblStudents
                                            where s.StudentNumber == long.Parse(username)
                                            select s).First();
                        new StudentForm().Show();
                    }
                    else if (student.userType.Equals("ADMIN"))
                    {
                        new AdminForm().Show();
                    }
                    else if (student.userType.Equals("FACULTY"))
                    {
                        new StaffFormMain().Show();
                    }
                }
                else
                {
                    MessageBox.Show("Invalid username or password", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("Invalid username or password.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
    }

StudentForm.cs

public StudentForm()
    {
        this.selectedStudent = (from s in DatabaseHelper.db.tblStudents
                               where s.StudentNumber == 2000013113
                               select s).First();
        InitializeComponent();
        materialSkinManager = MaterialSkin.MaterialSkinManager.Instance;
        materialSkinManager.EnforceBackcolorOnAllComponents = true;
        materialSkinManager.AddFormToManage(this);
        materialSkinManager.Theme = MaterialSkin.MaterialSkinManager.Themes.LIGHT;
        materialSkinManager.ColorScheme = new MaterialSkin.ColorScheme(MaterialSkin.Primary.Indigo500,
            MaterialSkin.Primary.Indigo700,
            MaterialSkin.Primary.Indigo100,
            MaterialSkin.Accent.Pink200,
            MaterialSkin.TextShade.WHITE);
    }

    private void RefreshCartList()
    {
        DgvCartList.Rows.Clear();
        subTotal = 0;
        foreach (OrderDetail item in cartList)
        {
            DgvCartList.Rows.Add(item.itemName,
                item.quantity,
                item.pricePerUnit,
                item.total);
            subTotal += item.total;
        }
        BtnCheckout.Enabled = cartList.Count > 0;
        BtnClearCart.Enabled = cartList.Count > 0;
        BtnRemoveItem.Enabled = cartList.Count > 0;
        LabelSubTotal.Text = cartList.Count > 0 ? subTotal.ToString() : "";
    }

    private void ClearCart()
    {
        cartList.Clear();
        RefreshCartList();
    }

    private void CmbItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        LabelStockCount.Text = itemList[CmbItems.SelectedIndex].stocks.ToString();
        LabelPrice.Text = itemList[CmbItems.SelectedIndex].price.ToString();
        BtnAddToCart.Enabled = true;
    }

    private void BtnAddToCart_Click(object sender, EventArgs e)
    {
        if (CmbItems.SelectedIndex != -1)
        {
            tblItem selectedItem = itemList[CmbItems.SelectedIndex];

            if (cartList.Count > 0)
            {
                foreach (OrderDetail item in cartList)
                {
                    if (item.itemID.Equals(selectedItem.ID))
                    {
                        if (item.quantity == 99)
                        {
                            MessageBox.Show("You cannot add more than 99 items of the same type in cart.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        if (item.quantity == selectedItem.stocks)
                        {
                            MessageBox.Show("You have reached the maximum number of stocks available.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        item.quantity++;
                        RefreshCartList();
                        return;
                    }

                }
            }
            cartList.Add(new OrderDetail
            {
                itemID = selectedItem.ID,
                itemName = selectedItem.itemName,
                quantity = 1,
                pricePerUnit = selectedItem.price
            });
            RefreshCartList();


        }
    }

    private void DgvCartList_RowEnter(object sender, DataGridViewCellEventArgs e)
    {
        selectedItemFromCart = DgvCartList.Rows[e.RowIndex].Cells[0].Value.ToString();
    }

    private void BtnRemoveItem_Click(object sender, EventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Are you sure you want to remove '" + selectedItemFromCart + "' from your cart?",
            "QUESTION", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (dialogResult == DialogResult.Yes)
        {
            foreach (OrderDetail item in cartList)
            {
                if (item.itemName.Equals(selectedItemFromCart))
                {
                    cartList.Remove(item);
                    RefreshCartList();
                    return;
                }
            }
        }
    }

    private void BtnClearCart_Click(object sender, EventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Are you sure you want to clear your cart?", "QUESTION", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (dialogResult == DialogResult.Yes)
        {
            ClearCart();
        }
    }

    private void BtnCheckout_Click(object sender, EventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Are you sure you want to checkout? You cannot reverse this action once done.", "QUESTION", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (dialogResult == DialogResult.Yes)
        {
            var newOrder = new tblOrder
            {
                studentId = selectedStudent.StudentNumber,
                orderStatus = "PENDING",
                orderDate = DateTime.Today.Date,
                totalPrice = subTotal

            };
            DatabaseHelper.db.tblOrders.InsertOnSubmit(newOrder);
            DatabaseHelper.db.SubmitChanges();

            var st = (from tbl in itemList
                     join cart in cartList on tbl.ID equals cart.itemID
                     select new { 
                         tbl.ID,
                         cart.quantity
                     }).ToList();

            foreach(var item in st)
            {
                var reduceStock = (from s in DatabaseHelper.db.tblItems
                                  where s.ID == item.ID
                                  select s).First();
                reduceStock.stocks -= item.quantity;
                
            }

            DatabaseHelper.db.SubmitChanges();

            foreach (OrderDetail item in cartList)
            {
                var newOrderDetail = new tblOrderDetail
                {
                    orderIdRef = newOrder.ID,
                    itemID = item.itemID,
                    itemName = item.itemName,
                    quantity = item.quantity,
                    pricePerUnit = item.pricePerUnit,
                    totalPrice = item.total,
                    orderStatus = "PENDING"

                };
                DatabaseHelper.db.tblOrderDetails.InsertOnSubmit(newOrderDetail);
            }
            DatabaseHelper.db.SubmitChanges();

            MessageBox.Show("Order placed!", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
            MessageBox.Show("Please save this document and/or print it and show it to the cashier.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information);
            using (PrintForm frm = new PrintForm())
            {
                frm.PrintInvoice(newOrder.studentId,
                fullName.Trim(),
                newOrder.ID,
                newOrder.orderDate.ToString("MM-dd-yyyy"),
                subTotal,
                cartList);
                frm.ShowDialog();
            }
            ClearCart();
            
        }
    }

    private void MStudentForm_Load(object sender, EventArgs e)
    {
        LabelStudentNum.Text = selectedStudent.StudentNumber.ToString();
        
        if (selectedStudent.MiddleName.ToString().Length == 0)
        {
            fullName = selectedStudent.FirstName.ToString() + " " + selectedStudent.LastName.ToString();
        }
        else
        {
            fullName = selectedStudent.FirstName.ToString() + " " + selectedStudent.MiddleName.ToString() + " " + selectedStudent.LastName.ToString();
        }
        LabelName.Text = fullName.Trim();
        LabelCourse.Text = selectedStudent.Course.ToString();
        LabelGender.Text = selectedStudent.Gender.ToString();

        switch (selectedStudent.Course.ToString())
        {
            case "BSIT":
                courseCategory = "IT";
                break;
            case "BSHM":
                courseCategory = "HM";
                break;
            case "BSTM":
                courseCategory = "TM";
                break;
            case "BACOMM":
                courseCategory = "AB";
                break;
        }

        var allItems = from item in DatabaseHelper.db.tblItems
                       where item.category == courseCategory
                       || item.category == "General"
                       || item.gender == selectedStudent.Gender
                       select item;

        foreach (var item in allItems)
        {
            tblItem item1 = new tblItem();
            item1.ID = item.ID;
            item1.itemName = item.itemName + " " + item.size;
            item1.category = item.category;
            item1.size = item.size;
            item1.price = item.price;
            item1.stocks = item.stocks;
            if (item1.stocks > 0)
                itemList.Add(item1);
            else
                notAvailableItemsList.Add(item1.itemName);
        }

        itemList = itemList.OrderBy(y => y.itemName).ToList();
        notAvailableItemsList = notAvailableItemsList.OrderBy(y => y).ToList();
        
        if(notAvailableItemsList.Count > 0)
        {
            string items = "";
            foreach(string item in notAvailableItemsList)
            {
                items += item;
                items += "\n";
            }
            MessageBox.Show("Not available items are:\n" + items, "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        foreach (var item in itemList)
        {
            CmbItems.Items.Add(item.itemName);
        }
    }

    private void MStudentForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Are you sure you want to sign out?", "SIGN OUT", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (dialogResult == DialogResult.Yes)
        {
            this.Hide();
            new LoginForm(false).Show();
        }
        else
        {
            e.Cancel = true;
        }
    }

    private void DgvCartList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            string name = DgvCartList.Rows[e.RowIndex].Cells[0].Value.ToString();
            int stockItem = 0;
            foreach (var item in itemList)
            {
                if (name.Equals(item.itemName))
                {
                    stockItem = item.stocks;
                    break;
                }
            }

            if (DgvCartList.Rows[e.RowIndex].Cells[1].Value == null)
            {
                MessageBox.Show("You cannot leave this field empty.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                RefreshCartList();
                return;
            }

            int quantity = int.Parse(DgvCartList.Rows[e.RowIndex].Cells[1].Value.ToString());

            if (quantity > 99)
            {
                MessageBox.Show("You cannot add more than 99 items of the same type in cart.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                RefreshCartList();
                return;
            }
            if (quantity > stockItem)
            {
                MessageBox.Show("You have reached the maximum number of stocks available.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                RefreshCartList();
                return;
            }
            foreach (OrderDetail item in cartList)
            {
                if (item.itemName.Equals(name))
                {
                    item.quantity = int.Parse(DgvCartList.Rows[e.RowIndex].Cells[1].Value.ToString());
                    RefreshCartList();
                }

            }

        }
    }

错误

    System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>ProwareSystem.exe</AppDomain><Exception><ExceptionType>System.ArgumentException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Cannot bind to the property or column itemDescription on the DataSource.
Parameter name: dataMember</Message><StackTrace>   at System.Windows.Forms.BindToObject.CheckBinding()
   at System.Windows.Forms.BindToObject.SetBindingManagerBase(BindingManagerBase lManager)
   at System.Windows.Forms.Binding.SetListManager(BindingManagerBase bindingManagerBase)
   at System.Windows.Forms.ListManagerBindingsCollection.AddCore(Binding dataBinding)
   at System.Windows.Forms.BindingsCollection.Add(Binding binding)
   at System.Windows.Forms.BindingContext.UpdateBinding(BindingContext newBindingContext, Binding binding)
   at System.Windows.Forms.Control.UpdateBindings()
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ListControl.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnParentBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.set_BindingContextInternal(BindingContext value)
   at System.Windows.Forms.ContainerControl.set_BindingContext(BindingContext value)
   at System.Windows.Forms.ContainerControl.get_BindingContext()
   at System.Windows.Forms.Control.get_BindingContextInternal()
   at System.Windows.Forms.Control.get_BindingContext()
   at System.Windows.Forms.Control.UpdateBindings()
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ListControl.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnParentBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ContainerControl.OnCreateControl()
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message&amp;amp; m)
   at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.Form.WmShowWindow(Message&amp;amp; m)
   at System.Windows.Forms.Form.WndProc(Message&amp;amp; m)
   at MaterialSkin.Controls.MaterialForm.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</StackTrace><ExceptionString>System.ArgumentException: Cannot bind to the property or column itemDescription on the DataSource.
Parameter name: dataMember
   at System.Windows.Forms.BindToObject.CheckBinding()
   at System.Windows.Forms.BindToObject.SetBindingManagerBase(BindingManagerBase lManager)
   at System.Windows.Forms.Binding.SetListManager(BindingManagerBase bindingManagerBase)
   at System.Windows.Forms.ListManagerBindingsCollection.AddCore(Binding dataBinding)
   at System.Windows.Forms.BindingsCollection.Add(Binding binding)
   at System.Windows.Forms.BindingContext.UpdateBinding(BindingContext newBindingContext, Binding binding)
   at System.Windows.Forms.Control.UpdateBindings()
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ListControl.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnParentBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.set_BindingContextInternal(BindingContext value)
   at System.Windows.Forms.ContainerControl.set_BindingContext(BindingContext value)
   at System.Windows.Forms.ContainerControl.get_BindingContext()
   at System.Windows.Forms.Control.get_BindingContextInternal()
   at System.Windows.Forms.Control.get_BindingContext()
   at System.Windows.Forms.Control.UpdateBindings()
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ListControl.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnParentBindingContextChanged(EventArgs e)
   at System.Windows.Forms.Control.OnBindingContextChanged(EventArgs e)
   at System.Windows.Forms.ContainerControl.OnCreateControl()
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message&amp;amp; m)
   at System.Windows.Forms.Control.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.Form.WmShowWindow(Message&amp;amp; m)
   at System.Windows.Forms.Form.WndProc(Message&amp;amp; m)
   at MaterialSkin.Controls.MaterialForm.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp;amp; m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;amp; m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll
Cannot bind to the property or column itemDescription on the DataSource.

【问题讨论】:

  • 错误消息很清楚,您实际上自己回答了这个问题:检查所有文件 - 特别是 XAML 文件 - 仍然应该有一个“itemDescription”需要重命名为“itemName”。您应该真正考虑一下您的表定义,并使其尽可能保持不变,以避免将来出现这种工作量。附言这种问题可能更适合 Stackexchanges 的代码审查
  • 我使用 linq to sql DBML 文件,但找不到这样的东西。我认为当我尝试刷新它时它会自动更新,但似乎我找不到错误在哪里。

标签: c# .net windows forms winforms


【解决方案1】:

看来我只需要将 Designer.cs 中的数据绑定从“itemDescription”更改为“itemName”。

我通过这行代码解决了。

this.CmbItems.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.tblItemBindingSource, "itemName", true));

我要感谢大家分享他们的知识。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多