0

所以我有这个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>

我想知道有什么方法可以访问这个下拉列表并用数据填充它。我尝试了以下代码,但它们都不起作用,都返回错误“对象引用未设置为实例”:

      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"));

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

4

1 回答 1

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"));
    }
}
于 2014-11-17T11:13:14.050 回答