2009-11-24 1 views
0

여기에 코드입니다. 내가 얻는 것은 argumentException이 "입력 문자열이 올바른 형식이 아니 어서 MY_FLOAT colomn에 < 2.111을 저장할 수 없습니다. 예상 유형이 두 배입니다."비교 데이터 세트 열 유형

정말로 필요한 것은 열 유형을 유형과 비교하여 올바른 유형으로 열을 할당하는 것입니다.

제 영어가 좋지 않아서 이것이 분명하기를 바랍니다.

+0

thisRow [strDataLines [I]] 당신은 당신이 –

+0

당신이 당신의 테이블 구조와 일부 샘플 데이터를 게시 할 수 있다고 생각 데이터를 저장하지 않는 것 같은 보인다? –

답변

0

올바르게 이해하면 코드 조각의 기능적 복사본을 작성하고 형식 변환을 올바르게 처리하도록 수정했습니다. 당신은 정말로 두 가지를 놓쳤습니다 :

. # 1 - 서수로 열을 인덱싱하고 해당 정보를 사용하여 열 유형을 얻었습니다. 그런 다음 칼럼에 색인을 생성 한 정보를 설정합니다. 아래 'columnName'변수를 도입하여이를 수정했습니다.

. # 2 - 문자열 입력을 원하는 열 유형으로 올바르게 변환하려면 아래 그림과 같이 System.Convert.ChangeType (object, Type) 메서드 만 사용해야합니다.

static void Main() 
    { 
     DataSet ds = new DataSet(); 
     DataTable dt = ds.Tables.Add("Repartition"); 
     DataColumn col; 

     col = dt.Columns.Add("ID_USAGER", typeof(int)); 
     col = dt.Columns.Add("TestString", typeof(string)); 
     col = dt.Columns.Add("TestInt", typeof(int)); 
     col = dt.Columns.Add("TestDouble", typeof(double)); 

     string testData = "TestString;TestInt;TestDouble"; 
     testData += Environment.NewLine + "Test1;1;1.1"; 
     testData += Environment.NewLine + "Test2;2;2.2"; 

     Test(ds, new StringReader(testData)); 
    } 

    public static void Test(DataSet thisDataSet, StringReader sr) 
    { 
     string[] strDataLines = sr.ReadLine().Split(';'); 
     string strReadDataLine; 
     strReadDataLine = sr.ReadLine(); 

     while (strReadDataLine != null) 
     { 
      string[] strReadDataLineSplited = strReadDataLine.Split(';'); 

      DataRow thisRow = thisDataSet.Tables["Repartition"].NewRow(); 
      DataTable item = thisDataSet.Tables["Repartition"]; 
      for (int i = 0; i < strDataLines.Length; i++) 
      { 
       string columnName = strDataLines[i]; 
       //#1 Don't use this as Columns[i] may not be Columns[columnName] 
       //DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[i]; 
       DataColumn thisColomn = thisDataSet.Tables["Repartition"].Columns[columnName]; 
       //#2 Assing to the results of the string converted to the correct type: 
       thisRow[strDataLines[i]] = System.Convert.ChangeType(strReadDataLineSplited[i], thisColomn.DataType); 
      } 
      thisRow["ID_USAGER"] = 1; 

      thisDataSet.Tables["Repartition"].Rows.Add(thisRow); 

      strReadDataLine = sr.ReadLine(); 
     } 
    }