Click here to Skip to main content
15,919,358 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to fetch some ids in to the string in form as follows:

'1','2','3'

I used the following way but its not giving the appropriate result.
C#
foreach (DataRow drCont in dt.Rows)
       {
           sOptInContactsIDs = "'" + sOptInContactsIDs + "'"+  drCont["ContactID"] + "',";
       }

       sOptInContactsIDs = sOptInContactsIDs.Replace("'',", "");
       int icount = sOptInContactsIDs.Length;
       sOptInContactsIDs = sOptInContactsIDs.Remove(icount - 1);


I am missing some logic.....Plz help me on this.
Thanks.
Posted
Comments
vr reddy 9-Sep-14 5:39am    
please send me your result

Try this:
C#
string sep = "";
StringBuilder sb = new StringBuilder();
foreach (DataRow drCont in dt.Rows)
   {
   sb.AppendFormat("{0}'{1}'", sep, drCont["ContactID"]);
   sep = ",";
   }
sOptInContactsIDs = sb.ToString();
 
Share this answer
 
Comments
lovejeet0707 9-Sep-14 5:39am    
Perfect...........Spot On...!!
Thanks Sir :)
OriginalGriff 9-Sep-14 5:49am    
You're welcome!
Neetin_1809 9-Sep-14 6:25am    
Sir ,
Clear & Easy To UnderStand Code . mY vOTE oF 5
Hello,
In C# .I will Suggest You To Use String.To Count the length Simply Use Spilt Function.
Declare
C#
string sOptInContactsIDs   = string.Empty; ;

First Check whether that Column Has value or not.

C#
     foreach (DataRow drCont in dt.Rows)
       {
             if(drCont["ContactID"]!=DBNull.Value)
                 {
                      if(sOptInContactsIDs ==  string.Empty)
                          sOptInContactsIDs = "'"+ drCont["ContactID"] +"'";
                       else
                           sOptInContactsIDs = sOptInContactsIDs +","  +"'"+ drCont["ContactID"] +"'";
                  }
   }//Close of for each loop
//For Spilting It 
         int icount = sOptInContactsIDs.Split(',');

Intially When First Row is Fetched & Value Is 1
then
sOptInContactsIDs="'"+1+"'"= '1'
For Second time assume value is 2
sOptInContactsIDs = '1'+","+"'"+2+"'"='1','2'


If you are aware of string.Format Use that One For Better Exection.
If Possible Use For Loop Instead of ForEach.

I have Used that Code in My Project . i have collected all Ids in Array. Then Using For Loop I have collected the value in string and inserted comma after that.

Hope It Helps You.

Happy Coding :-)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900