我在gridview中的一个TemplateField里放了两个DROPDOWNLIST,分别绑定年和月。
当我要保存当前gridview中的信息时,代码如下:
 foreach (GridViewRow gvRow in GridView1.Rows)
{
      foreach (Control ctr in gvRow.Cells[2].Controls)//cell[2]中放了两个DROPDOWNLIST
                {
                    DropDownList yearList = ctr as DropDownList;
                    DropDownList monthList = ctr as DropDownList;
                    if (yearList != null && monthList != null )
                    {
                        effectiveDate = DateTime.Parse("1/" + monthList.Text + "/" + yearList.Text);
                    }
                     }
}
我用单步调试,发现monthList.Text  和yearList.Text的值都是绑定年的那个DROPDOWNLIST的selectValue,难道每个模板列中只能放一个DROPDOWNLIST的吗?

解决方案 »

  1.   

    .......
    这个代码明显有问题啊:
     DropDownList yearList = ctr as DropDownList; 
                        DropDownList monthList = ctr as DropDownList
    在循环里,两个DropdownList都是相同的赋值,那么两个肯定是相同的值了
    1、使用FindControl找到
    2、DropDownList yearList = gvRow.Cells[2].Control[0];
    DropDownList monthList = gvRow.Cells[2].Control[1];
      

  2.   

    DropDownList yearList = gvRow.Cells[2].Control[0]; 
    DropDownList monthList = gvRow.Cells[2].Control[1];------------------------------
    这样写不对啊
    错误信息:
    Error 39 Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.DropDownList'. An explicit conversion exists (are you missing a cast?) E:\radar\document\source code\Radar\Rate_Detail.aspx.cs 106 32 E:\...\Radar\
      

  3.   

    DropDownList yearList = (DropDownList)gvRow.Cells[2].Control[0];  
    DropDownList monthList = (DropDownList)gvRow.Cells[2].Control[1]; 
      

  4.   

    如果你GridView中的DropDownList给了ID,也可以通过FindControl来找到:
    假设ID为YearList
    DropDownList yearList = (DropDownList)gvRow.Cells[1].FindControl("YearList");
    或者
    DropDownList yearList = (DropDownList)gvRow[行的索引].FindControl("YearList");