So I have a gridview that I'm populating in the code behind, listening to a drop down to know what to populate. That part works fine. But when I fire the rowediting event from the gridview, the databind process throws a NullReferenceException error.
Here is the page:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="categories">
<h1>Categories</h1>
<asp:DropDownList ID="ddlCategories"
runat="server"
OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
</div>
<div id="products">
<h1>Products</h1>
<asp:GridView ID="gvProducts"
runat="server"
AutoGenerateColumns="false"
OnRowEditing="gvProducts_RowEditing"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
OnRowCancelingEdit="gvProducts_RowCancelingEdit"
OnRowUpdating="gvProducts_RowUpdating">
<Columns>
<asp:BoundField
DataField="Category.Name"
HeaderText="Category" />
<asp:BoundField
Datafield="Name"
HeaderText="Name"/>
<asp:BoundField
Datafield="Description"
HeaderText="Description"/>
<asp:BoundField
DataField="Price"
HeaderText="Price"
DataFormatString="{0:c}"
HtmlEncode="False"/>
<asp:ImageField
DataImageUrlField="ImageURL"
HeaderText="Picture"></asp:ImageField>
<asp:CheckBoxField
DataField="Active"
Text="Active"
HeaderText="Status"/>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
And here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategoryList();
BindProductList();
}
}
protected void BindCategoryList()
{
ddlCategories.DataTextField = "Name";
ddlCategories.DataValueField = "CategoryID";
ddlCategories.DataSource = CategoryDB.GetCategories();
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem(string.Empty));
ddlCategories.SelectedIndex = 0;
}
protected void BindProductList(int categoryID = 0)
{
gvProducts.DataSource = ProductDB.GetProductsByCategory(categoryID);
gvProducts.DataBind();
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
BindProductList(Int32.Parse(ddlCategories.SelectedValue));
}
protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
gvProducts.EditIndex = e.NewEditIndex;
BindProductList(Int32.Parse(ddlCategories.SelectedValue));
}
The error occurs in the BindProductList() method, but only when called from gvProducts_RowEditing. Otherwise, it works fine. When I debug, I can see that it definitely is passing the correct categoryID value, and it does not throw an error until the DataBind call, which means that it can still find gvProducts for the DataSource() call.
Any ideas? Thanks.
Edit: here is the categorydb class and getcategories method.
public class CategoryDB
{
public static List<Category> GetCategories()
{
using (var db = new ProductContext())
{
return (from c in db.Categories
orderby c.Name
select c).ToList<Category>();
}
}