Santanu Maulik
Santanu Maulik

Reputation: 111

How to comma-separate a set of strings without the final comma

int rowPosition = 0;
string WorkerName = "";
DataTable dtAllotedManpower = new DataTable();
dtAllotedManpower.Columns.Add("WorkerName");
foreach (GridViewRow row in GridViewTotalManpower.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        DataRow drAllotedManpower = dtAllotedManpower.NewRow();
        CheckBox chkChild = (CheckBox)GridViewTotalManpower.Rows[rowPosition].FindControl("chkChild");
        if (chkChild.Checked == true)
        {
            WorkerName = Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()) + "," + WorkerName;

        }
        rowPosition++;
    }
    hidfWorker.Value = WorkerName;

I have Written the following piece of code. My hidden field values are coming like this

"HARSH,RIMA,"

But i want the value "HARSH,RIMA" (without ',' after the last word). how to construct the code for that ? . there will be no 'comma' after last word .

Upvotes: 2

Views: 2058

Answers (4)

Mukesh Modhvadiya
Mukesh Modhvadiya

Reputation: 2178

Use StringBuilder instead of string if you are frequently changing the string like in loops, because when you use string it will create new string object every time you changes it,

StringBuilder workerName = new StringBuilder();

And in your loop

workerName.Append(Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()) + ",");

Then trim last ',' character using TrimEnd method

hidfWorker.Value = workerName.ToString().TrimEnd(',');

Hope this helps.

Upvotes: 1

Dhaval Patel
Dhaval Patel

Reputation: 7601

you can use the substring method

hidfWorker.Value=WorkerName.Substring(0,WorkerName.Length-1);

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

Add them to a collection then use string.Join:

var list = new List<string>();

foreach (GridViewRow row in GridViewTotalManpower.Rows) {
    // ...other code here...
    list.Add(Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()));
}

 hidfWorker.Value = string.Join(", ", list);

Upvotes: 12

schei1
schei1

Reputation: 2487

You can use string.TrimEnd()

hidfWorker.Value = WorkerName.TrimEnd(','); 

This will remove the last comma from the string.

Upvotes: 2

Related Questions