原數據三列:`數量`、`種類`、`顏色`。
目標顯示兩列:`數量`、`種類(顏色)`。
**不要在前端控件中硬拼**,而在**數據層/業務層**組裝好顯示所需的模型,再綁定給 GridView。
public class ProductViewModel {
public int Quantity { get; set; }
public string CategoryWithColor { get; set; } // 已拼接好
}
var list = dbContext.Products.Select(p => new ProductViewModel {
Quantity = p.Quantity,
CategoryWithColor = p.Category + "(" + p.Color + ")"
}).ToList();
gridView.DataSource = list;
gridView.DataBind();
// GridView RowDataBound 事件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
var row = (DataRowView)e.Row.DataItem;
e.Row.Cells[1].Text = row["Category"] + "(" + row["Color"] + ")";
e.Row.Cells[2].Visible = false; // 隱藏原顏色列
}
}
**最佳實踐:數據層組裝 ViewModel,前端純綁定。**