在C#中定位asp.net gridview模板字段内的下拉列表

时间:2014-11-17 10:45:13

标签: c# asp.net gridview findcontrol rowdatabound

所以我有这个gridview,如下所示:

<asp:GridView ID="gridDetaljiNarudzbe" AutoGenerateColumns="false" AllowPaging="true" PageSize="10" runat="server" OnRowCommand="gridDetaljiNarudzbe_RowCommand" OnPageIndexChanging="gridDetaljiNarudzbe_PageIndexChanging" OnRowDataBound="gridDetaljiNarudzbe_RowDataBound">
    <Columns>
       <asp:BoundField DataField="Naziv" HeaderText="Naziv" />
       <asp:BoundField DataField="Sifra" HeaderText="Šifra" />
       <asp:BoundField DataField="Cijena" HeaderText="Cijena" />
       <asp:BoundField DataField="Kolicina" HeaderText="Količina" />
            <asp:TemplateField HeaderText="Ocjena">
            <ItemTemplate>
                <asp:DropDownList  ID="DropDownList1" runat="server"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
      <asp:TemplateField>
          <ItemTemplate> 
              <asp:LinkButton ID="btnOcijeni" title="Ocijeni proizvod" CommandName="OcijeniCommand" CommandArgument='<%# Eval("ProizvodID") %>' runat="server"><img src="../images/ocijeni.png" /></asp:LinkButton>
          </ItemTemplate>
      </asp:TemplateField>
    </Columns>
</asp:GridView>

我想知道是否有任何方法可以访问此下拉列表并使用数据填充它。我已经尝试了以下代码,但它们都没有工作,都返回错误&#34;对象引用未设置为intstance&#34;:

      DropDownList drop =  gridDetaljiNarudzbe.FindControl("DropDownList1") as DropDownList;

然后我会做以下事情:drop.Items.Add(new ListItem("test"));

我也尝试过RowDataBound事件,但它还没有工作......

DropDownList droplist = e.Row.FindControl("DropDownList1") as DropDownList;

然后使用以下代码填充网格,以便测试它是否有效:

drop.Items.Add(new ListItem("test"));

但这些都不起作用......我还想知道如何从这个下拉列表中获取值,并在有人从中获取内容时将其插入到数据库中。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

这应该这样做

foreach (GridViewRow gr in gridDetaljiNarudzbe.Rows)
{
    DropDownList drop =  gr.FindControl("DropDownList1") as DropDownList;
    drop.Items.Add(new ListItem("test"));
}

或者如果您想在RowDataBound事件

中执行此操作
protected void gridDetaljiNarudzbe_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drop =  e.Row.FindControl("DropDownList1") as DropDownList;
        drop.Items.Add(new ListItem("test"));
    }
}