2
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 .

4 Answers 4

12

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);
Sign up to request clarification or add additional context in comments.

1 Comment

this is the best way to do this
2

You can use string.TrimEnd()

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

This will remove the last comma from the string.

2 Comments

@SimonWhitehead: Indeed. You do have the proper solution :-)
Santanu also refer the answer by @Simon
1

you can use the substring method

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.