Search code examples
c#datagridviewdatagridviewcolumn

DataGridView change a cell content that's condition up to another cell


I have a list of products and I am trying to add them into a datagridview. Each product has a property like id, name, brand, price, stockAmount, isPackaged, and product type properties. What i want is to make invisible the IsPackaged boolean and if that boolean is true change the productType to "packaged" if it is not make it "unpackaged", I dont want in each insertion typing the packageType. However, I get an error like "The name IsPackaged does not exist in the current context"

To hide the isPackage column i found a code that works fine: dataGridView1.Columns["IsPackaged"].Visible = false;

list.Add(new Product()
            {
                ID = 4,
                Name = "Ice Cream",
                Brand = "Magnum",
                Price = 12,
                IsPackaged = true,
                ProductType = IsPackaged ? "Packaged" : "Unpackaged" , //Here is the error
                StockAmount = 50,
            });


Solution

  • I could be mistaken, but it looks like ProductType should be a “non-settable” property since it is based on the IsPackaged property. In other words, whatever, IsPacked IS will determine what ProductType’s value is.

    In its current state the two variables appear redundant and could be set into an inconsistent state. Example… the user could set IsPackaged to false, then turn around and set ProductType to “Packaged”! How would you know which one was correct?

    You may want to change the ProductType of the Product class to maintain a consistent state like…

    public string ProductType {
      get {
        return IsPackaged ? "Packaged" : "Unpackaged";
      }
    }
    

    This way the “ProductType” is never “directly" set since it depends on what value IsPackaged is.

    This property will be displayed in the grid; however, the user will not be able to “change” it. And since you are making the IsPackaged column invisible, then there will be no way for the user to change it. So, I will assume there is missing info in your question in regard to “how” this is supposed to work. If it is for purely “display” purposes, then it should work. If you want the user to be able to “change” the IsPackaged value, then I would guess that it should be displayed to the user. Again, this is not clear.