views:

568

answers:

2

Hi all,

I have written some code to do a bulk update of a gridview. In the gridview one of my template fields has a drop downlist:

<asp:DropDownList ID="DDLCategories" runat="server" 
  DataSourceID="odsCategories" DataTextField="txtCategory" 
  DataValueField="intCategoryID" SelectedValue='<%# Bind("intCategoryID") %>'>
  <asp:ListItem Text="Please Select an item" Value ="-1"></asp:ListItem>
</asp:DropDownList>

In my database I have 800 records. However only a few of them have been assigned the value of "intCategoryID". The rest are NULL.

The whole reason of the bulk update is to update all of the "intCategoryID" fields and assign a category ID to each record.

Because not all od the "intCategoryID" have been assigned a value I am getting an error when I try to render the page. The dropdown list is failing. Here is the message:

'DDLCategories' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Is there a way I can assign the empty categories to the list item that has a value of "-1" I have created in the dropdownlist? IE If the "intCategoryID" ISNULL then have "Please Select an item" selected, otherwise select the selected value.

Thanks...

A: 

Check out this post. It overrides the binding method for the DDL and checks for the missing SelectedValue. You may have to modify it if you're not using a FormView, but I think you'll get a good start with that post.

Cory Larson
Thanks Cory for pointing me in the right direction, much appreciated...
Jason
A: 

I have tried to convert the code you pointed out to me, however I am still only new to C# and ASP.NET therefor I have some errors.

The code you pointed out refers to a formview, however I am tring to change it to a gridview.

Here is my code so far:

protected void GridView1_PreRender(object sender, EventArgs e)
    {
        DataRowView rowView = (DataRowView)(GridView1.DataItem);
        if ((rowView != null) &&
            ((DropDownList)(GridView1.FindControl("DDLCategories")).Items.FindByValue(rowView["intCategoryID"].ToString()) != null));
        {
            (DropDownList)(GridView1.FindControl("DDLCategories")).SelectedValue = rowView["Category"].ToString();
        }
    }



protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
    e.NewValues["intCategoryID"] = (DropDownList)(GridView1.FindControl("DDLCategories")).SelectedValue;
}

Could you please point out when I am creating errors.

Jason