获取子字符串会导致错误

本文关键字:错误 字符串 获取 | 更新日期: 2023-09-27 18:25:15

我有以下行:

if ( dataGridView1.Rows[i].Cells[0].Value.ToString().Length >= 13 ){      
                e.Graphics.DrawString
(dataGridView1.Rows[i].Cells[0].Value.ToString().Substring(0,14),
print6B, Brushes.Black, x-10, 130 + height);
                }
                else {

由于Substring方法,我得到了以下错误:索引和长度必须指字符串c#中的一个位置

获取字符串前14个字符的最佳方法是什么?

获取子字符串会导致错误

如果有14个字符,这会很好,但如果少于14个字符则不会。您可以编写自己的扩展方法:

public string SafeSubstring(this string text, int index, int count)
{
    // TODO: null checking
    return text.Length > index + count ? text.Substring(index, count)
                                       : text.Substring(index);
}

请注意,这只会帮助您避免由于计数而导致的异常——您仍然需要确保index是合适的。

我觉得不错。你确定你没有抓住标题行吗?这是处理网格视图时常见的错误。

if (dataGridView1.Rows[i].RowType == DataControlRowType.DataRow)
{
    if (dataGridView1.Rows[i].Cells[0].Value.ToString().Length > 13)
    {
        e.Graphics.DrawString(dataGridView1.Rows[i].Cells[0].Value.ToString().Substring(0,14), print6B, Brushes.Black, x-10, 130 + height);
    }
}

您可以在这里看到更多关于行类型的信息

首先检查字符串的长度-如果小于14个字符,则返回整个字符串,否则返回SubString(0,14)。

string strToWrite = string.Empty;
if(dataGridView1.Rows[i].Cells[0].Value.Length > 14){
   strToWrite = dataGridView1.Rows[i].Cells[0].Value.ToString().Substring(0,14);
else 
   strToWrite = dataGridView1.Rows[i].Cells[0].Value;
e.Graphics.DrawString(strToWrite, print6B, Brushes.Black, x-10, 130 + height);