[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5714
  • Last Modified:

Gridview - populating dropdownlist in codebehind

hi Guys,
I am having a nightmare with this, i really hate using gridviews.
Anyway, basically i have a dropdown list in a gridview, which i want to bind to a datasource and populate it from codebehind (this allows me to populate it from a file listing).

I have tried to populate the list in just about all the gridview events, rowupdating, databound etc but as soon as i hit edit in the gridview i get an error stating the selectedvalue does not exist - thats because it is trying to set the selectedvalue (needed to bind it) before i can populate it.

So summary:

I click on the gridview edit button, which event do i use to populate the dropdown - without getting the
"SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value"

god this should be so simple.
1 Solution
Raju SrivatsavayeSoftware EngineerCommented:
if your gridview has a autogenerated edit button then bind it in the row_editing event of the datagrid
Si_HibbardAuthor Commented:
Found solution.

First have to populate in the gridview databound event:

    protected void GridViewRowDataBound(object sender, GridViewRowEventArgs e)
        //GridView1.EditIndex = e.Row;

        //GridViewRow gvr = GridView1.Rows[GridView1.EditIndex];
        if (e.Row.RowType == DataControlRowType.DataRow)
            DropDownList ImageDropDown = (DropDownList)e.Row.FindControl("ImageDropDown");

            if (ImageDropDown != null)
                String[] files = Directory.GetFiles(Server.MapPath("../RightSideImages/"));
                String fileName;

                //DropDownList ImageDropDown = ((DropDownList)GridView1.FindControl("ImageDropDown"));
                //SmallImageList.Items.Add("-- Please Select --");

                foreach (string path in files)
                    fileName = Path.GetFileName(path);

Then have to catch the updating event and set the new value:

    protected void GridViewRowUpdating(object sender, GridViewUpdateEventArgs e)
        // value of template field has to be updated manually
        int iIdx = e.RowIndex;
        GridViewRow row = GridView1.Rows[iIdx];
        DropDownList ddl = (DropDownList)row.FindControl("ImageDropDown");
        e.NewValues["Filename"] = ddl.SelectedValue;
Closed, 500 points refunded.
Community Support Moderator

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now