[英]Change DataTable Column Value
我有一個這樣的數據表:
Attribute Percentage ReferenceAmount TaxAmount
------------ ------------ ---------------- -----------
Sales 5.00 5000 250
VAT 2.00 250 5
Discount 0 0 100
我想用一個 GridView 綁定這個 DataTable。 但是在 GridView 中,我不想顯示 0。而不是零,我只想將該單元格留空。 如果包含零,我不想顯示任何其他內容。 如何在 DataTable 中替換 EmptyString 而不是零?
我回答這個問題很晚,我知道答案已經被接受了。 但是在接受的答案中,您在數據綁定之后迭代行,然后設置值。
最好在 DataBinding 時替換該值。 它將克服 gridview 行迭代的額外開銷。
您可以使用 GridView 的RowDataBound
事件。 這是完整的代碼..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
if (dr["Percentage"].ToString() == "0")
{
((Label)e.Row.FindControl("lblPercentage")).Text = "";
//this is template field
//OR---If you don't use template field you can do like..--
e.Row.Cells[1].Text = "";
}
}
}
您可以輕松地將名為 PercentageDescription 的屬性添加為 String
public string PercentageDescription
{
return Percentage == 0 ? " " : Percentage.ToString();
}
以下 GridView DataBound 方法將遍歷 GridView 中的每個單元格,並將“0”替換為空字符串:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < row.Cells.Count - 1; i++)
{
if (row.Cells[i].Text == "0")
{
row.Cells[i].Text = "";
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.