eddyuk
eddyuk

Reputation: 4190

asp.net drop down list creation in grid view

I'm trying to create drop down list for each row on RowDataBound event. Drop down list

auto post back is enabled. When I change selection in drop down list, it doesn't go

to event.

I don't want to use javascript so looking for solution with postback.

Thanks

Upvotes: 0

Views: 1984

Answers (1)

Niranjan Singh
Niranjan Singh

Reputation: 18290

I suggest you to use Template Field in GridView and there you can place your drop-down List as:

<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:DropDownList Width="50" runat="server" 
   id="ddlYear" AutoPostBack="true" 
   OnSelectedIndexChanged="ddlYear_SelectedIndexChanged">
</asp:DropDownList> 

Then at RowDataBound add items to drop-downlist or bind it with some datasource.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Finding the Dropdown control in the row.
        DropDownList ddlYear= e.Row.FindControl("ddlYear");
        if (ddlYear!= null)
        {
            ddlYear.DataTextField = "Name";
            ddlYear.DataValueField = "YearID";
            ddlYear.DataSource = ds.Tables["years"];
            ddlYear.DataBind();
        }
    }
}

You can follow the @Madhu's specified link also..

As you are doing is not good approch to add Dropdown list dynamically at RowDataBound .. on every postback this event will recreate these drop down again.

Upvotes: 1

Related Questions