我有一个Gridview
<asp:GridView runat="server" ID="gvTrades" GridLines="None" CellPadding="0" CellSpacing="0" AutoGenerateColumns="true"></asp:GridView>
我正在尝试将第一列格式化为包含'%'的百分比。但是,我无法按名称访问该列。我想从代码隐藏中执行此操作,而不是在aspx页面中使用boundfield。
DataTable dt = SOME METHOD TO FILL UP THE DATATABLE;
gvTrades.DataSource = dt;
gvTrades.DataBind();
这就是我想要做的事情:
gvTrades.Columns["MyColumnName"].Text = {0:P};
答案 0 :(得分:1)
如果您对列索引进行硬编码没问题,可以在RowDataBound
事件中执行此操作:
<asp:GridView runat="server"
ID="gvTrades"
GridLines="None"
CellPadding="0"
CellSpacing="0"
AutoGenerateColumns="true"
OnRowDataBound="gvTrades_RowDataBound">
</asp:GridView>
protected void gvTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = String.Format("{0}%", e.Row.Cells[0].Text);
}
}
如果没有,您可以循环HeaderRow
的每个单元格以查找特定的列名称。找到正确的列后,您将获得所需的索引。这在GridView DataBound
方法中会更好,这样您就不必为每一行循环所有标题单元格。
<asp:GridView runat="server"
ID="gvTrades"
GridLines="None"
CellPadding="0"
CellSpacing="0"
AutoGenerateColumns="true"
OnDataBound="gvTrades_DataBound">
</asp:GridView>
protected void gvTrades_DataBound(object sender, EventArgs e)
{
int myIndex = 0;
foreach (DataControlFieldHeaderCell headerCell in gvTrades.HeaderRow.Cells)
{
if (headerCell.Text == "MyColumnName")
break;
myIndex++;
}
if (myIndex <= gvTrades.HeaderRow.Cells.Count - 1)
{
foreach (GridViewRow row in gvTrades.Rows)
{
row.Cells[myIndex].Text = String.Format("{0}%", row.Cells[myIndex].Text);
}
}
}