nnnn
nnnn

Reputation: 1051

Checking data with commas in a DataTable

I apologize for this newbie question, but I'm looking for a simple solution.
I want to write a function that will return a datatable.
Like this:

public static DataTable DataTableCommaReplce(DataTable dt){..}

The function will check each data in DataTable.
If data contained one or more commas, the function will make that data in double quote.
For Example:

you,me⇒"you,me"

What's the best way to write this function?
Can any body help me?


I had solved with this code, but I want more simple solution.
If possible, I want no looping.

public static DataTable DataTableCommaReplce(DataTable dt)
        {
            int col = dt.Columns.Count;
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < col; i++)
                {
                    if (dr[i].ToString().IndexOf(",") > 0)
                    {
                        dr[i] = "\"" + dr[i].ToString() + "\"";
                    }
                }
            }
            return dt;
        }

Upvotes: 2

Views: 1538

Answers (2)

Try the Following Code part. Hope it will help.

DataTable Tb = new DataTable();
for (int i = 0; i < Tb.Columns.Count; i++)
 {
    for (int j = 0; j < Tb.Rows.Count; j++)
     {

       if (Tb.Rows[j][i] != DBNull.Value)
       {
         if (Tb.Rows[j][i].ToString().IndexOf(',') != -1)
         {
          Tb.Rows[j][i] = "\"" + Tb.Rows[j][i].ToString() + "\"";
          }
       }
     }
 } 

Upvotes: 0

Jay Riggs
Jay Riggs

Reputation: 53603

This should work:

public static DataTable DataTableCommaReplce(DataTable dt) {
    foreach (DataRow row in dt.Rows) {
        foreach (DataColumn col in dt.Columns) {
            string s = row[col] as string;
            if (s != null) {
                if (s.Contains(',')) {
                    row[col] = string.Format("\"{0}\"", s);
                }
            }
         }
    }
    return dt;
}

Upvotes: 2

Related Questions