这是一段编历数据库充填treeview的程序, 以首字母做父结点. 我能保证数据库库信息的正常的.
我对读入的字符串进行substring处理获取首字符, 编译器老是报我出错, 为什么, 不可能有错呀.
编译器大哥放过我吧.string nch = rd["CName"].ToString();
nch = nch.Substring(0,1);  // 索引和长度必须引用该字符串内的位置。或是  string nch = rd["CName"].Substring(0,1); private void  Ref()
{//  SELECT CID, CName FROM Customer ORDER BY CName
this.tvCust.Nodes.Clear();
string ch = "";
int i = 0; this.cmdList.Connection.Open();
System.Data.SqlClient.SqlDataReader rd = this.cmdList.ExecuteReader();
while( rd.Read() )
{
string nch = rd["CName"].ToString();
nch = nch.Substring(0,1);  // 索引和长度必须引用该字符串内的位置。
if( nch != ch )
{
ch = rd["CName"].ToString().Substring(0,1);
TreeNode fnode = new TreeNode(ch);
this.tvCust.Nodes.Add(fnode);
i++;
}
//if( rd["CompanyName"].ToString().Substring(0,1) == ch )
if( rd["CName"].ToString().Substring(0,1) == ch)
{
TreeNode snode = new TreeNode( rd["CName"].ToString() );
snode.Tag = rd["CID"].ToString();
this.tvCust.Nodes[i-1].Nodes.Add(snode);
}
  }
rd.Close();
this.cmdList.Connection.Close();
}

解决方案 »

  1.   

    rd["CName"].ToString()是不是为空呢,它的长度必须大于1才可以用string nch = rd["CName"].Substring(0,1);,不然就会报超出索引的错误
      

  2.   

    最大的问题  rd["CName"].ToString()  肯定不为空.
    我的数据表中就这列有值, 其他的都为空.
      

  3.   

    我把while 循环中的语句换成
    string s = rd["CName"].ToString();
    this.txtID.Text = s; 
    this.txtName.Text = rd[0].ToString();
    this.txtOCount.Text = s.Substring(0,1);最后一句注释掉, 运行OK.  this.txtID.Text显示一个完整字符串.
    不注释  this.txtOCount.Text = s.Substring(0,1);  // 索引和长度必须引用该字符串内的位置。我他妈找谁惹谁了.