zoukankan      html  css  js  c++  java
  • 如何处理重命名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()]);
          }
       }
    }

  • 相关阅读:
    关于使用Java Mail进行邮件发送,抛出Could not connect to SMTP host: xx@xxx.com, port: 25的异常可能
    百度地图和solr展示资源和附近等功能的实现 四
    Python爬虫入门-3
    Python爬虫入门-2
    Python爬虫入门-1
    Python装饰器专题-限制函数调用次数(10s调用一次)
    32个Python爬虫项目让你一次吃到撑
    时间复杂度趣图分析
    各类数据库默认端口总结
    ansible使用三(ansible roles)
  • 原文地址:https://www.cnblogs.com/wangguowen27/p/2624421.html
Copyright © 2011-2022 走看看