如何根据Error Message()方法更改Gridview文本颜色?

时间:2011-09-08 03:48:48

标签: c# asp.net gridview colors

我有这些代码  在我的cs文件中:

   //A method to display errors in the gridview
    private string ErrorMessage(string input)

        {
            {
                //if there are null values, error message will be displayed.
                if (!string.IsNullOrEmpty(input))
                    return input;

            }
            return  "No value entered";// I am supposed to change this to red colour


        }

    public System.Drawing.Color InStockColor(string inStock)
    {
        return System.Drawing.Color.Red;
    } 




 // to read all lines of the posted csv file and put the lines in the grid view
        var data = File.ReadAllLines(Server.MapPath(FilePath))
            // to split the lines according to commas
          .Select(line => line.Split(','))

          .Select(columns => new { A = ErrorMessage(columns[0]), B = ErrorMessage(columns[1]), C = ErrorMessage(columns[2]), D = ErrorMessage(columns[3]), E = ErrorMessage(columns[4]), F = ErrorMessage(columns[5]), G = ErrorMessage(columns[6]), H = ErrorMessage(columns[7]), I = ErrorMessage(columns[8]) });


        myGridView.DataSource = data; 
        myGridView.DataBind();



<asp:GridView ID="myGridView" runat="server" CellPadding="4" 
    EnableModelValidation="True" ForeColor="#333333" GridLines="None" 
    Width="414px" align="center">
    <AlternatingRowStyle BackColor="White" />

    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

</asp:GridView>

到目前为止,我已经创建了一个可以改变文本颜色的方法。现在,我该如何实现这个方法?应该更改为红色的文本是“未输入值!”

1 个答案:

答案 0 :(得分:0)

这就是我解决问题的方法!

using System.Drawing;

private string ErrorMessage(string input, int rowNr, int colNr)          
{             
    if (!string.IsNullOrEmpty(input))
        return input;

    myGridView.Rows[rowNr].Cells[colNr].ForeColor = Color.Red;
    return  "No value entered";
}  

另一种方法是添加像这样的HTML标签......

using System.Drawing;

private string ErrorMessage(string input, int rowNr, int colNr)          
{             
    if (!string.IsNullOrEmpty(input))
        return input;
    return  "<font color='Red'>" + "No value entered" + "</font>";
} 

但我不建议使用这些代码,因为{@ 1}}已被弃用,并且您实际上已将该单元格的文本值设置为html代码。

希望这有帮助!

编辑:

你可以解释一下这段代码...... mabe提供了一些背景信息 这是什么语法?

你能解释一下.Select(...)命令它们是如何工作的吗?他们做了什么?

<font>