【问题标题】:Getting a substring results an error获取子字符串会导致错误
【发布时间】:2012-02-22 03:16:31
【问题描述】:

我有以下一行:

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 方法,我收到此错误: index 和 length 必须引用字符串 c# 中的某个位置

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

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    如果有 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 是合适的。

    【讨论】:

      【解决方案2】:

      我觉得很好。你确定你没有抓住标题行吗?这是处理gridview时的常见错误。

      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);
          }
      }
      

      你可以看到更多关于行类型here

      【讨论】:

      • 我上面有这个:for (int i = 1; i
      • 你确定它也没有抓住页脚(假设有一个)?
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:
        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);
        

        【讨论】:

          猜你喜欢
          • 2017-08-02
          • 2018-04-06
          • 2022-11-16
          • 1970-01-01
          • 2015-09-03
          • 1970-01-01
          • 1970-01-01
          • 2012-06-24
          • 2016-05-18
          相关资源
          最近更新 更多