日期:2014-05-18  浏览次数:20427 次

Gridview下的DropDownList问题,很郁闷.
GridView中的第条数据行都绑定了一个DropDownList,要取得DropDownList所在行的SelectedValue和DataKeys的值.
本来已经实现了.后来不记得改动了哪里又不能实现了.很郁闷.请各位指点一下.
/////////////////////////////////////
<asp:TemplateField>
  <ItemTemplate>
  <asp:DropDownList ID="ddlSubCht" runat="server" DataSourceID="objSubCht" DataTextField="SubName" DataValueField="SubId" AutoPostBack="True" OnSelectedIndexChanged="ddlSubCht_SelectedIndexChanged" >
  </asp:DropDownList>
  </ItemTemplate>
</asp:TemplateField>
////////////////////////////////////
C# code
 
protected void ddlSubCht_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < gvCategories.Rows.Count; i++)
            {
                DropDownList ddl = (DropDownList)gvCategories.Rows[i].FindControl("ddlSubCht");//问题1:在Debug下发现不能找到控件
                int ddlint = Convert.ToInt32(ddl.SelectedValue);//问题2:提示"未将对象引用设置到对象的实例"
                int key = (int)gvCategories.DataKeys[i].Value;//问题3:总是返回的同一个值.我想返回的是每行对应的DataKeys

                lbl.Text= ddlint+"_"+key+"_"+isSingle.ToString();//输出
            }
        }


------解决方案--------------------
LZ是不是少了他的Cell【】
------解决方案--------------------
方法位置不对吧
------解决方案--------------------
1,方法位置不对
2,确实少cell[]
你不精确到单元格是找不到控件的
------解决方案--------------------
C# code

protected void ddlSubCht_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList ddl = (DropDownList)sender;
   int ddlint = Convert.ToInt32(ddl.SelectedValue);
   int key = (int)gvCategories.DataKeys[(ddl.Parent as GridViewRow).RowIndex].Value;
   ..
}

------解决方案--------------------
C# code

foreach (GridViewRow row in this.GvCaseApplyList.Rows)
{
CheckBox chkPunish = (CheckBox)row.FindControl("chkCaseApply");
id=this.GvCaseApplyList.DataKeys[row.RowIndex][1].ToString();
}

------解决方案--------------------
DropDownList ddl = (DropDownList)gvCategories.Rows[i].FindControl("ddlSubCht");//问题1:在Debug下发现不能找到控件
定位不对吧....你这对应的是第几行...单元格呢?
------解决方案--------------------
DropDownList ddl = gvCategories.Rows[i].FindControl("ddlSubCht") as DropDownList;//

另外还要精确到cell
------解决方案--------------------
探讨
C# code
protected void ddlSubCht_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int ddlint = Convert.ToInt32(ddl.SelectedValue);
int key = (int)gvCategories.DataKeys[(ddl.Parent as GridViewRow).RowIndex].Value;
..
}

------解决方案--------------------

DropDownList ddl = (DropDownList)gvCategories.Rows[i].FindControl("ddlSubCht");
测试了一下,可以找到控件啊,你看看是不是数据什么的出错了.
------解决方案--------------------