所以我有一个网格视图,我在后面的代码中填充,听一个下拉菜单来知道要填充什么。那部分工作正常。但是当我从 gridview 触发 rowediting 事件时,数据绑定过程会引发 NullReferenceException 错误。
这是页面:
<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>
这是背后的代码:
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));
}
错误发生在 BindProductList() 方法中,但仅在从 gvProducts_RowEditing 调用时发生。否则,它工作正常。当我调试时,我可以看到它肯定传递了正确的 categoryID 值,并且在调用 DataBind 之前它不会抛出错误,这意味着它仍然可以找到用于 DataSource() 调用的 gvProducts。
有任何想法吗?谢谢。
编辑:这里是 categorydb 类和 getcategories 方法。
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>();
}
}