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

  • 相关阅读:
    Longest Common Substring
    未完成 Anagrams
    strStr
    vim的学习笔记
    Compare Strings
    Two Strings Are Anagrams
    KMP算法
    [ 力扣活动0314 ] 300. 最长上升子序列
    [ 力扣活动0317 ] 1160. 拼写单词
    [ 力扣活动0313 ] 169. 多数元素
  • 原文地址:https://www.cnblogs.com/wangguowen27/p/2624421.html
Copyright © 2011-2022 走看看