开发者

Change value of control inside a gridview templatefield itemtemplate

hi I have this gridview like this.

<asp:DropDownList ID="triggerDropDown" runat="server" AutoPostBack="true" onselectedindexchanged="triggerDropDown_SelectedIndexChanged">

<asp:GridView ID="myGridView" run="server">
     <Columns>
          <asp:TemplateField HeaderText="Column 1">
               <ItemTemplate>
                   <asp:DropDownList ID="myDropDown1" runat="server" />
               </ItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="Column 2">
               <ItemTemplate>
                   <asp:DropDownList ID="myDropDown2" runat="server" />
               </ItemTemplate>
          </asp:TemplateField>
     </Columns>
</asp:GridView>

now, when I change my triggerDropDown I want to change also all of the DropDowns inside Column 1 how can I do that?

protected void triggerDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
    // what should I do开发者_运维知识库 here?
}


Inside your event method you should access the DropDownList that resides within each row of the GridView. Doing this you can bind each DropDownList to whatever data you want.

This link shows you how to do that:

http://www.velocityreviews.com/forums/t191319-need-help-with-accessing-a-control-within-a-template-field.html

Basically:

  • Iterate over each row of your GridView;

  • Find the DropDownList control with something like:

    DropDownList mddl = GridView.Rows[2].FindControl("myDropDown1");

  • Bind new data to mddl.


The gridview is very likely not what you want here. The way to change the value of a control contained in a row is usually through grabbing a handle to the desired control using e.Item.FindControl() from within the ItemDataBound event of the gridview.

The problem with your approach is that you're wanting a control outside of the gridview (triggerDropDown) to interact with a single row of the gridview. Do you want the first row, first column, last row, first column or first column for each of the items in the grid? It's probably better you take the target of your trigger dropdown and place it outside of the gridview and deal with it directly.

If you really intend to change items in a row in the grid consider doing so in the ItemDataBound event of the gridview and you'll find lots of examples out there.


Actually I can use GridViewRow :) I just have to find the GridViewControl and get its Rows attribute which is a GridViewRow and now I can do a foreach of each row.

foreach (GridViewRow gridViewRow in (this.FindControl("myGridView") as GridView).Rows)
{
    // I can see all elements of my row here as if I am traversing on GridViewEvents
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜