I think you can generate the default values(for Columns Qty In Stock, Status) in your datasource(In dataset or database) & then you can bind with Datagridview.
Have a look at these (Involves dynamic columns creation too)
101 Ways to Manipulate the DataGridView Control - Part 1[
^]
101 Ways to Manipulate the DataGridView Control - Part 2[
^]
[EDIT]
I think you forgot to fill the value for
DataPropertyName property, so assign the value for Design columns + runtime columns.
Call the below method in form_load in your application.
public void BindGridView()
{
DataTable table = new DataTable();
table.Columns.Add("FoodName", typeof(string));
table.Columns.Add("FoodType", typeof(string));
table.Columns.Add("QtyInStock", typeof(int));
table.Columns.Add("Status", typeof(string));
string[] arrFoodName = new string[] { "Olives", "Soup", "Caprese", "Bruschetta", "Mushroom", "Antipasto", "Scallops", "Calamari", "Crab Avocado", "Pizza Bread" };
string[] arrFoodType = new string[] { "Starter", "Other" };
bool IsStock = false;
long Qty = 0;
for (int i = 0; i < 10; i++)
{
if (i > 5)
{
Qty = i * 5;
IsStock = true;
}
if (IsStock)
{
table.Rows.Add(arrFoodName[i], arrFoodType[1], Qty, "Always On Stock");
}
else
{
table.Rows.Add(arrFoodName[i], arrFoodType[0], 0, "No Stock");
}
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = table;
DataGridViewTextBoxColumn ColFoodQtyStock = new DataGridViewTextBoxColumn();
DataGridViewTextBoxColumn ColFoodStatus = new DataGridViewTextBoxColumn();
ColFoodStatus.HeaderText = "Status";
ColFoodStatus.DataPropertyName = "Status";
ColFoodStatus.Name = "Status";
ColFoodQtyStock.HeaderText = "Quantity In Stock";
ColFoodQtyStock.DataPropertyName = "QtyInStock";
ColFoodQtyStock.Name = "QtyInStock";
dataGridView1.Columns.AddRange(ColFoodQtyStock, ColFoodStatus);
}
Now It will display four columns with data.
Note : check the column names mine with yours.
Sample for adding dynamic columns & rows to datatable
DataTable dt = new DataTable();
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow.Table.Columns.Add("QtyInStock");
myNewRow.Table.Columns.Add("Status");
myNewRow["QtyInStock"] = 1;
myNewRow["Status"] = "No Stock" ;
dt.Rows.Add(myNewRow);
[EDIT]
[Final EDIT]
If you want the 0, "Always on Stock" as default for your newly generated run time columns(QtyInStock & Status) then change the query dude.
string foodTypeSql = @"SELECT FoodName, FoodType, 0 AS QtyInStock, 'Always on Stock' AS Status FROM Food WHERE FoodType = @foodType";
You can
CASE statement[
^] for defining the row values based on conditions. That's it.
[/Final EDIT]
BTW I'm glad you came with good question with your snippet(I like the style of your question), please keep continue always dude.
Cheers. :thumbsup: