C# 将背景色添加到以大写字母开头的gridview的所有单元格值
我是ASP.NET和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
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
}