Groups | Blog | Home
all groups > c# > march 2004 >

c# : Concatenate a datareader list into a string


Tom
3/31/2004 9:31:06 PM
Hi

I want to retrieve database data and concatenate them to a string. Here is my code

[code

string sql = "Select phone From users where userid=1 or userid=2 or userid=3 or userid=4

SqlDataReader dr = null

dr = SqlHelper.ExecuteReader(DBConnection.ConnString, CommandType.Text, sql)

ArrayList list = new ArrayList(0)
d

list.Add(dr["phone"].ToString()); //runtime error her
} while (dr.NextResult())

string[] array = (string[])list.ToArray(typeof(string));
string result = String.Join(", ", array)

[/code

I want to concatenate the phone number in DB to a string like
result = "123456,234567,345678,456789

How should I modify the code

Marcin_Grzêbski
4/1/2004 9:55:03 AM
Hi Tom,

[quoted text, click to view]

object phoneObj;

//> do

while( dr.NextResult() )

[quoted text, click to view]
// list.Add(dr["phone"].ToString()); //runtime error here

phoneObj=dr["phone"];

// write phones that aren't empty
if( phoneObj!=DBNull.Value ) {
list.Add(phoneObj.ToString().Trim());
// Trim() only if your numbers should not
// have empty spaces
}

//> } while (dr.NextResult());

}

[quoted text, click to view]
//> string result = String.Join(", ", array);

string result = String.Join(",", array);
// lifting change

[quoted text, click to view]

If It doesn't do what you want then feedback on group.

Regards

Dmitry Kostenko
4/1/2004 10:57:19 AM
[quoted text, click to view]

I think you should check if dr["phone"] == null before calling ToString():
if (dr["phone"] != null)

[quoted text, click to view]

Marcin_Grzêbski
4/1/2004 11:27:56 AM
My fault... loop should be

do {
....
}
while(...)

;)

AddThis Social Bookmark Button