【问题标题】:C# Winform How to Generate fix character?C# Winform 如何生成修复字符?
【发布时间】:2012-09-26 09:36:46
【问题描述】:

我生成数字 8,9,A,B (Int64)

但我需要

00000008

00000009

0000000A

0000000B

000001ED

此代码:

        int count = 1;
        sb = new StringBuilder();
        sb.Append("SELECT max(Numb) FROM tblAs");

        string sql = sb.ToString();
        cmd.CommandText = sql;
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Conn;
        count = (int)cmd.ExecuteScalar();
        int newCount = count;
        int i;


        for (i = 0; i < dataGridView1.Rows.Count; i++)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                newCount = newCount + 1;

                Int64 numTag;
                string cTag = Convert.ToString(newCount);
                numTag = Int64.Parse(cTag);
                cTag = numTag.ToString("X");

                if (cTag.Length < 8)
                {
                    int countchar = 8 - cTag.Length;
                    for (i = 1; i <= countchar; i++)
                    {
                        cTag = "0" + cTag;
                        dataGridView1.Rows[i].Cells[3].Value = cTag;
                    }
                }
            }

错误行: dataGridView1.Rows[i].Cells[3].Value = cTag; 消息:索引超出范围。必须是非负数且小于集合的大小。 参数名称:索引

感谢您的宝贵时间:)

【问题讨论】:

  • 行索引从零开始,而不是从 1
  • 总的来说,我认为您应该熟悉调试工具。大多数时候,just stepping into code, watching variables and comparing expected values and actual values in your head 可以解决问题。通过这样做,您会惊讶地发现代码中的所有错误如此之快。

标签: c# winforms c#-4.0 if-statement for-loop


【解决方案1】:

为自己节省一些工作和 .NET Framework 的 use the built-in features

// automatically pads the number with up to 8 leading zeros
cTag = numTag.ToString("X8");  

【讨论】:

    【解决方案2】:

    嵌套 fors 使用相同的变量i

    for (i = 0; i < dataGridView1.Rows.Count; i++)
    

    for (i = 1; i <= countchar; i++)
    

    这就是你得到Index was out of range. Must be non-negative and less than the size of the collection的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 2021-06-20
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多