I want to use a dropdownlist on a gridview... I have the following code from asp.net
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.
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());
}
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