MKX2015
MKX2015

Reputation: 175

Converting Data Table to List and vice versa

I don't know what's wrong. I have a SQL Statement and an adapter

 DataTable datTableCur = new DataTable();
 datTable = new DataTable();

 sqlCmd = new SqlCommand(@"SELECT DISTINCT [" + form1.getCol() + "] FROM [" + form1.getTableName3() + "]", connection);
 sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
 sqlDatAdapter.Fill(datTableCur);

Since the format is "float" in SQL I convert it to "Double" in C# and put every element of the column in a List

 List<Double> convertCol = new List<Double>();
 List<Double> convertedCol = new List<Double>();

 foreach (DataRow row in datTableCur.Rows)
 {
     convertCol.Add((double)row[0]);
 }

Now I want to check if the elements have "," and if that's the case I want to replace the "," with a ".", so I convert every single element into a String, check this case, replace the char, convert it back to Double and store it in another List

  String convertToString;
  Double storeDouble;
  Double convertBackToDouble;

  for (int i = 0; i < convertCol.Count; i++)
  {
      storeDouble = convertCol[i];
      convertToString = storeDouble.ToString("0.######");

      if (convertToString.Contains(","))
      {
          convertToString.Replace(",", ".");
          convertBackToDouble = Convert.ToDouble(convertToString);
          convertedCol.Add(convertBackToDouble);
      }
      else 
      {
          convertedCol.Add(convertCol[i]);
      }
  }

and now here's my problem. I want to put that back into a DataTable, and put that in a ListBoxbut that doesn't work. I get an ArgumentException and the error, that the input array is longer than the number of columns in the table.

datTable.Rows.Add(form1.getCol());

for (int j = 1; j < convertedCol.Count; j++)
{
    datTable.Rows.Add(convertedCol[j]);
}

form1.colList.DisplayMember = form1.getCol();
form1.colList.ValueMember = "Column";
form1.col.DataSource = datTable;

Upvotes: 1

Views: 779

Answers (1)

Mahesh
Mahesh

Reputation: 8892

The error you are facing due to you need to add the column first in the datatable you are adding or to replace the precious orignal value column you need to add the column with same name

DataColumn dc = new DataColumn("col2");
dc.DataType = typeof(double);
table.Columns.Remove("col2");
table.Columns.Add(dc);

and you can set the values then.

You can shorten your loop like below to get your list of double values.(Not tested may have syntax error).

var result doubleValueList = dt.AsEnumerable()
         .Select(x=> new {double.Parse(x.ToString("0.######").Replace(",", "."))})
         .ToList();

Upvotes: 1

Related Questions