0

I want to replace a string with a new value through a SqlDataReader, but the DataReader return 2 values, 2 and 4, the replacement works fine, replace the string with the value 2, but no with the 4 value.

First i create a List from a class, then i add the values of the DataReader to the List:

listaTan.Add(new ListaTan { Tanques = dr["Num"].ToString() })

Then i use a for loop to replace the string:

for (int i = 0; i < listaTan.Count; i++)
{
    body = body.Replace("#Num#", listaTan[i].Tanques);
}

But always replace the first value and no the second.

The purpose is to send emails with the two values, ie send 2 emails, 1 email with the value 2 and another with the value 4.

Now, I send 2 emails but always with value 2 and no for the other values, because of the replace it doesn't work properly.

Thank You

habib
  • 2,366
  • 5
  • 25
  • 41
Isaías Orozco Toledo
  • 1,919
  • 5
  • 19
  • 35
  • 2
    Unlike JavaScript, C#'s `Replace` will replace every instance of the search string with the replacement string. [This question](https://stackoverflow.com/questions/141045/how-do-i-replace-the-first-instance-of-a-string-in-net) might help you. – ProgrammingLlama Aug 08 '18 at 01:45
  • @John and for this case, how to "Replace" the dr[""].ToString(), because i read a html template and then i need to replace to populating the template and send the email – Isaías Orozco Toledo Aug 08 '18 at 01:51
  • 1
    IsaíasOrozcoToledo, @John is right. Try with a Regex like in this answer: https://stackoverflow.com/a/3012392/2025364 – Adam Calvet Bohl Aug 08 '18 at 04:11

1 Answers1

0

Can you simply do something like this:

DataTable dt = new DataTable();
dt.Load(dataReader);// i'm not sure, Load() or LoadData()

foreach (DataRow row in dt.Rows)
{
    row[fieldname] = row[fieldname].Replace("#Num#")
}

Like directly modifying the datatable without creating a new list.

Gauravsa
  • 6,330
  • 2
  • 21
  • 30