Marci Marci - 29 days ago 11
C# Question

How to replace strings in a List

I got values from a .csv file and put them into a datagridview, but I'd like to replace some values before to fill my datagridview.

This is the screen of my .csv file:

enter image description here

and this is my code to try to do it:

string FileName = @"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");

conn.Open();

OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);

DataSet ds = new DataSet("Temp");
adapter.Fill(ds);

conn.Close();

DataTable dt = ds.Tables[0];

List<HT> matchhtList = new List<HT>();
matchhtList = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString(),
Away = dr["Away"].ToString(),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
Segno = dr["Segno"].ToString(),
odd1 = dr["odd1"].ToString(),
oddx = dr["oddx"].ToString(),
odd2 = dr["odd2"].ToString()

}).ToList();

StringBuilder mystring = new StringBuilder("matchhtList");
mystring = mystring.Replace("Rosenborg", "Rihanna")
.Replace("Start", "Stop")
.Replace("Brann", "Circus");

dataGridView2.DataSource = mystring;


Please, if my question is not clear, tell me before to put "-1", I'll try to explain better my question. Thank you very much!

Answer

you can replace the the text when you build the list

matchhtList = (from DataRow dr in dt.Rows
                   select new HT()
                   {
                       Home = dr["Home"].ToString().Replace("Rosenborg", "Rihanna"),
                       Away = dr["Away"].ToString().Replace("Start", "Stop").Replace("Brann", "Circus"),
                       ScoreHome = dr["ScoreHome"].ToString(),
                       ScoreAway = dr["ScoreAway"].ToString(),
                       Segno = dr["Segno"].ToString(),
                       odd1 = dr["odd1"].ToString(),
                       oddx = dr["oddx"].ToString(),
                       odd2 = dr["odd2"].ToString()

                   }).ToList();

dataGridView2.DataSource = matchhtList;