Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将背景色添加到以大写字母开头的gridview的所有单元格值_C#_Asp.net - Fatal编程技术网

C# 将背景色添加到以大写字母开头的gridview的所有单元格值

C# 将背景色添加到以大写字母开头的gridview的所有单元格值,c#,asp.net,C#,Asp.net,我是ASP.NET和C#的新手。我想为gridview的所有单元格值添加背景色,这些单元格值以大写字母开头。以下是我的源代码: protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { TableCell cell = e.Row.C

我是ASP.NET和C#的新手。我想为gridview的所有单元格值添加背景色,这些单元格值以大写字母开头。以下是我的源代码:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TableCell cell = e.Row.Cells[2];
                string entity = cell.Text.ToString();
                if (entity[0] >= 'A' && entity[0] <= 'Z')
                {
                  cell.BackColor = Color.Yellow;
                }  
            }
 }
受保护的void OnRowDataBound(对象发送方,GridViewRowEventArgs e)
{
如果(e.Row.RowType==DataControlRowType.DataRow)
{
TableCell cell=e.Row.Cells[2];
字符串实体=cell.Text.ToString();

如果(实体[0]>='A'&&entity[0]='A'&&entity[0]问题在这一行:

if (entity[0]...
如果单元格的值为null或空,则实体将不包含任何元素。这将导致超出范围异常

您可以通过首先检查数组中是否有任何元素来解决此问题

if (!string.IsNullOrEmpty(entity) && entity[0] >= 'A' && entity[0] <= 'Z')
{
    //your code here
}
如果(!string.IsNullOrEmpty(entity)&&entity[0]>='A'&&entity[0]
cell.Text.ToString()
返回空字符串,如下所示:“”。问题是在该单元格中没有任何值,因此当您尝试访问字符串中的第一个位置时,它会抛出该异常。在第87行,异常消息非常清楚


解决方法确实是检查是否为null或空。

char
有一个
IsUpper
方法。您可以使用
char.IsUpper(entity[0])
,只要确保
entity
不为null且至少包含1个字符即可。这里不需要括号:(entity[0]>='A'&&entity[0]你的代码没有添加到以大写字母开头的单元格中!@mynhylisti你已经拥有的代码应该这样做。我只是为你得到的错误提供了一个解决方案。
if (!string.IsNullOrEmpty(entity) && entity[0] >= 'A' && entity[0] <= 'Z')
{
    //your code here
}