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;
我写了下面这段代码。我隐藏的字段值就像这样
"苛刻,RIMA,"
但我想要价值" HARSH,RIMA" (没有','在最后一个字之后)。如何构建代码? 。将不会有逗号'在最后一句话之后。
答案 0 :(得分:12)
将它们添加到集合中,然后使用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);
答案 1 :(得分:2)
答案 2 :(得分:1)
你可以使用子串方法
hidfWorker.Value=WorkerName.Substring(0,WorkerName.Length-1);
答案 3 :(得分:1)
如果你经常像循环一样更改字符串,请使用StringBuilder而不是字符串,因为当你使用字符串时,它会在每次更改时创建新的字符串对象,
StringBuilder workerName = new StringBuilder();
在你的循环中
workerName.Append(Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()) + ",");
然后修剪最后的&#39;&#39;使用TrimEnd方法的字符
hidfWorker.Value = workerName.ToString().TrimEnd(',');
希望这有帮助。