Search This Blog

Wednesday, March 30, 2011

DropDownList in Gridview EditItemTemplate value Selected


In the gridview we can use textbox by default for the edit template, that is to edit a row we can have textbox. Some times we may need of a dropdownlist in the edit template of the gridview, By the time we have to use the edit template with a dropdownlist and we need to highlight the selected item in the dropdownlist for the edit item. For such scenario refer the following code lines for a better understanding.

GridView markups for the edit template:

</asp:TemplateField>
<asp:TemplateField HeaderText="Item Details">
<ItemTemplate><%# Eval("Item") %></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlItems" DataSource='<%# GetAllItems() %>' DataTextField="Item"
DataValueField="ItemID" SelectedValue='<%# Bind("ItemID") %>' runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>

In the code behind:

The method to get all the items details from the database must be a public method, that means the access modifier of the GetAllItems() method should be public. And its return type must a dataset or a datatable.


public DataSet GetAllItems()
{
try
{
DataSet dsItems = new DataSet();

//Your method to fill the dataset from the DataBase

ViewState["ItemTable"] = dsItems;
return dsItems;
}
catch (Exception ex)
{
throw ex;
}

1 comment:

  1. Below code will work anyhow.


    .aspx






    .cs
    protected void GridViewUser_RowEditing(object sender, GridViewEditEventArgs e)
    {
    GridViewUser.EditIndex = e.NewEditIndex;
    LoadUserList();


    //Get the list of Company with ID from BLL
    var dSource = CompanyDetails.GetActiveCompanyList();

    //Find the DropDown Control in Grid view
    DropDownList ddl = (DropDownList)(GridViewUser.Rows[GridViewUser.EditIndex].FindControl("ddlCompanyList"));

    //Chek if Control found in gridview
    if (ddl != null)
    {
    ddl.DataTextField = "Name";
    ddl.DataValueField = "ID";
    ddl.DataSource = dSource;
    ddl.DataBind();
    }
    //Find the Hidden filed in Gridview
    HiddenField hdnID = new HiddenField();
    hdnID = (HiddenField)GridViewUser.Rows[GridViewUser.EditIndex].FindControl("hdnCompanyID");

    //Set the selected value of dropdown list with compare to Hidden field
    ddl.SelectedValue = hdnID.Value.ToString();
    }
    // Jagdeep Mankotia

    ReplyDelete

Note: Only a member of this blog may post a comment.