Using Dropdownlist in a gridview Asp.Net?

2019-03-02 15:44发布

I want to use a dropdownlist on a gridview... I have the following code from asp.net

<asp:GridView ID="grdvEventosVendedor" runat="server" AllowPaging="True" 
                AutoGenerateColumns="False" CellPadding="4" DatakeyNames="idCita"
                EmptyDataText="No Hay Eventos Para Este Vendedor" ForeColor="#333333" 
                GridLines="None" AllowSorting="True"
                onpageindexchanging="grdvEventosVendedor_PageIndexChanging" 
                onrowcommand="grdvEventosVendedor_RowCommand" 
                onsorting="grdvEventosVendedor_Sorting" CellSpacing="1" HorizontalAlign="Center">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775"/>

                <Columns>
                    <asp:TemplateField HeaderText="" ItemStyle-Width="35px">
                        <ItemTemplate>
                            <asp:ImageButton ID="imgBtnEdicEvento" runat="server" 
                                CommandArgument='<%# Eval("idCita")%>' CommandName="Edicion" 
                                Height="32px" ImageUrl="~/img/pencil_32.png" Width="32px" />
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="" ItemStyle-Width="35px">
                        <ItemTemplate>
                            <asp:ImageButton ID="imgBtnDelete" runat="server"
                                CommandName="Borrar" 
                                ImageUrl="~/img/1385_Disable_16x16_72.png" 
                                onclientclick="return confirm('¿Desea eliminar el registro?');" 
                                CommandArgument='<%# Eval("idCita")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:BoundField DataField="Cliente" HeaderText="Cliente" InsertVisible="False" ReadOnly="True" SortExpression="Cliente" ItemStyle-Width="50px" />
                    <asp:BoundField DataField="Empresa" HeaderText="Empresa" InsertVisible="False" ReadOnly="True" SortExpression="Empresa" ItemStyle-Width="50px"/>
                    <asp:BoundField DataField="Telefono" HeaderText="Telefono" InsertVisible="False" ReadOnly="True" SortExpression="Telefono" ItemStyle-Width="50px"/>
                    <asp:BoundField DataField="Nextel" HeaderText="Nextel" InsertVisible="False" ReadOnly="True" SortExpression="Nextel" ItemStyle-Width="50px"/>
                    <asp:BoundField DataField="Tipo" HeaderText="Tipo" InsertVisible="False" ReadOnly="True" SortExpression="Tipo" ItemStyle-Width="50px"/>
                    <asp:BoundField DataField="Descripcion" HeaderText="Descripcion" InsertVisible="False" ReadOnly="True" SortExpression="Descripcion" ItemStyle-Width="100px"/>

                    <asp:TemplateField HeaderText="Fecha" SortExpression="Fecha" ItemStyle-Width="50px">
                        <ItemTemplate>                                            
                            <%# DataBinder.Eval(Container.DataItem, "Fecha", "{0:dd/MM/yyyy}")%>
                        </ItemTemplate>

                        <EditItemTemplate>                                        
                            <asp:TextBox ID="tbxFecha"  runat="server" Text='<%#Bind("Fecha","{0:dd/MM/yyyy}") %>' ValidationGroup="gpEdicionAgenda">
                            </asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>

                    <asp:BoundField DataField="HoraInicio" HeaderText="Hora" InsertVisible="False" ReadOnly="True" SortExpression="HoraInicio" ItemStyle-Width="50px"/>
                    <asp:BoundField DataField="Lugar" HeaderText="Lugar" InsertVisible="False" ReadOnly="True" SortExpression="Lugar" ItemStyle-Width="50px"/>

                    <asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
                        <ItemTemplate>
                            <asp:DropDownList ID="dpdListEstatus" runat="server">
                                <asp:ListItem>Pendiente</asp:ListItem>
                                <asp:ListItem>Atendido</asp:ListItem>
                            </asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="CRM" ItemStyle-Width="25px">
                        <ItemTemplate>
                            <asp:ImageButton ID="imgBtnCRM" runat="server"
                                CommandArgument='<%# Eval("IdCliente")%>' CommandName="CRM" 
                                ImageUrl="~/img/activar.png" Width="16px" Height="16px" />
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="VM" ItemStyle-Width="25px">
                        <ItemTemplate>
                            <asp:ImageButton ID="imgBtnVerMas" runat="server"
                                CommandArgument='<%# Eval("IdCliente")%>' CommandName="VerMas" 
                                ImageUrl="~/img/search.png" Width="16px" Height="16px" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>

                <EditRowStyle BackColor="#999999" Font-Size="Small" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" Font-Size="Larger" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" Font-Size="Small" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>

The part where it says is the part where I want the ddl to be...

You'll might've also noticed that I use a total of 4 buttons for edit, delete, etc... However I guess that's another story...

I want it to do a couple of things... first of, you'll notice that I have the dropdownlist with 2 values... that's because I get a datasource from a query, and those are the 2 possible values that this column can get...

So #1 should be... how can I make that the Ddl's Selected Value is the one I get from the query....

and #2 I can manually change the value of the ddl, so I want it to make a postback and update that specific row with the new value (the reason I need the postback would be so I can trigger for example a ddl ONSELECTEDINDEX CHANGED and therefore use the cs file to create a new query, update the row, and then refresh the gridview again)

I suppose that all of this might have something to do with rowcommand, just like the way the other 4 buttons work.

I'm using C# on this, so It would be helpful if you can help me using C# if you're method involves the cs file...

Thanks

3条回答
贪生不怕死
2楼-- · 2019-03-02 16:07

You can use GridView RowDataBound event to access drop down list, similarly set selectedindexchanged event for the dropdownlist.

Refer to this link below which shows the basics of the solutions you will need

http://www.codeproject.com/Articles/53559/Accessing-a-DropDownList-inside-a-GridView

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-02 16:07
This is what I did that worked for me:

**Snippet from aspx:**

  <asp:TemplateField HeaderText="RECORD_STATUS" SortExpression="RECORD_STATUS">
     <EditItemTemplate>
        <asp:DropDownList  runat="server" ID="ddlRecStatus"                                                SelectedIndex='<%# GetselectedRecStatus(Eval("RECORD_STATUS")) %>'
                                    DataSource = '<%# Recs_Status %>' />
                            </EditItemTemplate>
  </asp:TemplateField>

**Snippet from code-behind:**

 protected void grdSAEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //Get the refernce to the list control
            DropDownList ddlRecStatus = (DropDownList)(grdSAEdit.Rows[e.RowIndex].FindControl("ddlRecStatus"));

            // Add it to the parameters
            e.NewValues.Add("RECORD_STATUS", ddlRecStatus.Text);

        }

        protected string[] Recs_Status
        {
            get { return new string[] {  "A", "E", "V", "Z" }; }
        }

        protected int GetselectedRecStatus(object status)
        {
            return Array.IndexOf(Recs_Status, status.ToString());
        }
查看更多
劫难
4楼-- · 2019-03-02 16:18

You should use the OnRowDatabound event on the GridView. Like:

<asp:GridView ID="grdvEventosVendedor" OnRowDatabound="grdvEventosVendedor_RowDataBound">
        <asp:TemplateField HeaderText="Estado" ItemStyle-Width="50px">
            <ItemTemplate>
                <asp:DropDownList ID="dpdListEstatus" runat="server" OnSelectedIndexChanged="dpdListEstatus_SelectedIndexChanged" AutoPostBack="True">
                    <asp:ListItem>Pendiente</asp:ListItem>
                    <asp:ListItem>Atendido</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
</asp:GridView>

Then in the .cs backend code you should find the control and set it's selected value based on the dataitem values.

protected void grdvEventosVendedor_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList dpdListEstatus = e.Row.FindControl("dpdListEstatus") as DropDownList;
        dpdListEstatus.SelectedValue = DataBinder.Eval(e.Row.DataItem, "FieldName").ToString();
    }
}


protected void dpdListEstatus_SelectedIndexChanged(object sender, EventArgs e)
{
    //your logic goes here
}

You can set the SelectedIndexChanged on your dropdown in the ASPX code and in that piece of backend code you can continue your logic. Ow, and don't forget to set the autopostback = true on your dropdown.

查看更多
登录 后发表回答