locked
how to get specific column from datatable to array RRS feed

  • Question

  • User450763225 posted

    Hi, I am trying to get a column which has 4 rows into an array. Here is my code which doesn't work. The error is "can not convert char[] to string []". I have to use string[].

     DataTable dt = new DataTable();
                dt = this.FavoritesUtility.GetFavoriteGroupSearchResult(SearchText, SearchType, LimitToList, UseSearchOption, Guid.Empty, ref FavoriteGroupGrid.MyXMLInfoObject.LayoutXMLInfo, 0);
                foreach (DataRow dr in dt.Rows)
                {
                    string[] CellValue = dr["UserGUID"].ToString().ToArray();
                }

    Friday, August 17, 2012 5:01 PM

Answers

  • User3866881 posted

    string[] CellValue = dr["UserGUID"].ToString().ToArray();

    Your Guid means xxx-xxxxx-xxxxxxxxxxxx——all in all, it should be splitted by "-",So please use Split method instead:

     DataTable dt = new DataTable();
                dt
    = this.FavoritesUtility.GetFavoriteGroupSearchResult(SearchText, SearchType, LimitToList, UseSearchOption, Guid.Empty, ref FavoriteGroupGrid.MyXMLInfoObject.LayoutXMLInfo, 0);
               
    foreach (DataRow dr in dt.Rows)
               
    {
                   
    string[] CellValue = dr["UserGUID"].ToString().Split("-");
               
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 18, 2012 9:50 PM

All replies

  • User1264447444 posted

    You have dr["UserGUID"].ToString() inside a foreach loop and that will give you a string and then you are calling ToArray() on it.This will take the string and get a character array of it and hence the error.

    Here's a better way to do this.

    http://stackoverflow.com/questions/6127028/datatables-rows-first-column-to-string-array


    Friday, August 17, 2012 5:30 PM
  • User450763225 posted

    Thanks for your advice. I tried that, but it failed. The error is" can to convert GUID to String". For my case, I just want to put some Guid values in an array, is there better way ? Thanks

    Friday, August 17, 2012 5:52 PM
  • User3866881 posted

    string[] CellValue = dr["UserGUID"].ToString().ToArray();

    Your Guid means xxx-xxxxx-xxxxxxxxxxxx——all in all, it should be splitted by "-",So please use Split method instead:

     DataTable dt = new DataTable();
                dt
    = this.FavoritesUtility.GetFavoriteGroupSearchResult(SearchText, SearchType, LimitToList, UseSearchOption, Guid.Empty, ref FavoriteGroupGrid.MyXMLInfoObject.LayoutXMLInfo, 0);
               
    foreach (DataRow dr in dt.Rows)
               
    {
                   
    string[] CellValue = dr["UserGUID"].ToString().Split("-");
               
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 18, 2012 9:50 PM