分享到: 百度 更多

如何处理重命名DataSet对象的列名所导致的System.ArgumentException错误

我们在dataset中创建一个datatable列时,列名会添加到两个索引的位置,case-sensitive index 和case-insensitive index,当进行列的重命名时,新的名字不会添加到case-insensitive index,所以,当我们给列重新命名时,列名就变成case-sensitive 。

解决办法很简单:ds = ds.Copy();

for example : 下面的代码就会导致这个错误

using System;
using System.Data.SqlClient;
using System.Data;

namespace ConsoleApplication1
{
   class Class1
   {
      [STAThread]
      static void Main(string[] args)
      { 
         SqlConnection cn;
         //Connect to SQLServer.
         cn = new SqlConnection();
         cn.ConnectionString = "data source=YourSQLServer;integrated security=SSPI;persist security info=False;initial catalog=Northwind";
        
         SqlDataAdapter da;
         da = new SqlDataAdapter("select * from products", cn);
          
         DataSet ds;
         ds = new DataSet();

         da.Fill(ds, "Products");

         String colname;
         colname = ds.Tables[0].Columns[0].ColumnName;

        //Display the data in the the first row of the first column.
         Console.WriteLine(ds.Tables[0].Rows[0][colname.ToLower()]);
         Console.ReadLine();

         //Change the column names.
         int i;
         for (i =0;i<= (ds.Tables[0].Columns.Count - 1);i=i+1)
            ds.Tables[0].Columns[i].ColumnName = "C" + i.ToString();
             
         colname = ds.Tables[0].Columns[0].ColumnName;
         //display the data in the first row of the first column           
         Console.WriteLine(ds.Tables[0].Rows[0][colname.ToLower()]);
      }
   }
}

posted @ 2012-08-06 00:06  黑马_Summer  阅读(597)  评论(0编辑  收藏  举报
分享到: 百度 更多