Locating dropdownlist inside of asp.net gridview template field in C#

2.5k views Asked by At

So i have this gridview as shown below:

<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>

I was wondering is there any way I can access this dropdown list and populate it with data. I have tried the following codes, but none of them work, all returned error "object reference not set to an intstance":

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

Then I would do the following: drop.Items.Add(new ListItem("test"));

I have also tried with the RowDataBound event, but it also haven't worked...

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

then populating the grid with the following code just for sake of testing if it works:

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

But none of these worked... I would also like to know how to get a value from this dropdown and insert it into the DB when someone picks up something from it. Can someone help me out with this please?

1

There are 1 answers

4
ekad On BEST ANSWER

This should do it

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

or if you want to do it in RowDataBound event

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