【问题标题】:asp.net gridview formattingasp.net gridview 格式化
【发布时间】:2012-05-31 07:18:33
【问题描述】:

我有一个 gridview,它有三列 date、pnl、cumpnl 当使用代码应用于所有单元格时,我可以添加一些格式,例如

Protected Sub OnRowCreated(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        For Each cell As TableCell In e.Row.Cells
            cell.Font.Size = 10
            cell.HorizontalAlign = HorizontalAlign.Center
        Next
    End If

End Sub

在 For...Next 循环中,如何仅引用 pnl 和 cumpnl 列中的单元格?反正我看不到通过列标题名称或索引来引用单元格。

更新:

通过使用 RowDataBound 事件,我现在可以重置列中值的格式,但基于单元格值的前景色设置总是出错(“输入字符串格式不正确”)。另外,我正在对列索引进行硬编码。我需要一种基于列标题名称动态获取列索引的方法

Protected Sub gvDataRetrieval_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvDataRetrieval.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        For i As Integer = 1 To 2
            e.Row.Cells(i).Text = FormatCurrency(e.Row.Cells(i).Text, 2).ToString()
            If Double.Parse(e.Row.Cells(i).Text) < 0 Then e.Row.Cells(i).ForeColor = Drawing.Color.Red
        Next
 End If
End Sub

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    每个循环的外部:

    e.Row.Cells(index)
    

    例如。 添加标题工具提示:

        Protected Sub Grid1_RowCreated(ByVal sender As Object, ByVal e As GridRowEventArgs)
           //setting row cells
        If e.Row.RowType = DataControlRowType.DataRow Then
          For i As Integer = 1 To e.Row.Cells.Count
            If i = 1 Then
               e.Row.Cells(i).Font.Size= 8
            ELSE
               e.Row.Cells(i).Font.Size= 12
            END IF
          NEXT
        End If
        End Sub
    

    【讨论】:

    • 当然我可以对这些列的引用进行硬编码,但我希望能够动态测试列标题(并检索它的索引)并适当地格式化这些列
    • 您可以将模板列添加到您的网格中并执行以下操作:e.Row.FindControl("IDofyourcontrol")
    • 也许我不清楚,我希望能够遍历数据行中的每个单元格,并且只根据单元格所在的列更改格式。为此,我需要一个在迭代期间测试单元格所在列的方法。类似 If cell.column("pnl") then ForeColor= Color.Red
    【解决方案2】:

    卡皮尔的 C# 代码

            private void DataGrid1_RowCreated(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 1; i < e.Row.Cells.Count; i++)
                {
                    if (i == 1) { e.Row.Cells[i-1].Font.Bold = true; } else { e.Row.Cells[i-1].Font.Bold = false; }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2010-09-20
      • 2017-06-20
      相关资源
      最近更新 更多