-3

A for loop for the true condition sends a parameter to stored procedure and then required result is stored in a DataTable. Now my problem is at every loop the value in the DataTable gets refreshed with new value and previous value gets lost. How to retain all the value of true condition in the DataTable?

for (int i = 0; i < gridview1.Rows.Count; i++)
{
    string yojnaNo = "";
    CheckBox chl = (CheckBox)gridview1.Rows[i].Cells[0].FindControl("CheckBox1");

    if (chl != null)
    {
        if (chl.Checked == true)
        {
            int rowsNo = (Convert.ToInt16(chl.ToolTip) - 1); //Convert.ToInt16(SrNo);
            yojnaNo = ((Label)gridview1.Rows[rowsNo].FindControl("lblYojnaNo")).Text;
            sc.Add(yojnaNo);
        }
    }

    objyojnadetail4.YojnaNo = sc;
    DataTable city = objyojnadetail4.Selectcity();
}
4

1 回答 1

1

您可以将 city 的实例化放在外面,并在每个循环中将每一行添加到其中。你不会失去价值,相反,city每个循环都会变大。

DataTable city = new DataTable(); // instantiate here
for (int i = 0; i < gridview1.Rows.Count; i++)
{
    string yojnaNo = "";
    CheckBox chl = (CheckBox)gridview1.Rows[i].Cells[0].FindControl("CheckBox1");

    if (chl != null)
    {
        if (chl.Checked == true)
        {
            int rowsNo = (Convert.ToInt16(chl.ToolTip) - 1); //Convert.ToInt16(SrNo);
            yojnaNo = ((Label)gridview1.Rows[rowsNo].FindControl("lblYojnaNo")).Text;
            sc.Add(yojnaNo);
        }
    }

    objyojnadetail4.YojnaNo = sc;

    // this foreach loop may loop on anything the objyojnadetail4.Selectcity() provides
    // what was important is that, in this loop you insert each data into rows in city.
    foreach(var singleItem in objyojnadetail4.Selectcity().Rows)
    {
        city.Rows.Add(singleItem);
    }
}
于 2013-01-03T12:48:46.847 回答