Linq 2 SQL - Manual Databinding not working
I'm using linq2sql in my asp.net app. When using it with linq2sqldatasource object everything works, i mean i bind it without no code to a detailsview control. My idea is when i click a row in the detailscontrol e will load/add to the same page a customwebcontrol that will permit edit the data. For that i need to load some items to fill the dropdowns in that customcontrol, and in its load event i have the follwoing code that doesn't work and i can't see why. It raises a object null reference exception.
example:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//loads combobox with organizations
using (MyDataContext cdc = new MyDataContext())
{
var queryOrgs = from p in cdc.orgUnits
select p;
//Organizations
dropDownOrgs.DataSource = queryO开发者_如何学Pythonrgs.ToList();
dropDownOrgs.DataValueField = "orgUnitID";
dropDownOrgs.DataTextField = "orgUnitName";
dropDownOrgs.DataBind();
}
}
}
Anyone know what is happenning? Looks like when i want to bind all by myself manually something do not work :(
Hope you can help me.
Thanks. Teixeira
@Chalkey is correct. I have run into this error myself, where due to the fact that LINQ to SQL does "lazy" querying, it waits till the last minute to actually perform the query.
This means that it may wait until after the page_load function to do the query (and therefore outside of the using statement).
Therefore, return the data as a list with .ToList() to force it to run the query immediately.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//loads combobox with organizations
using (MyDataContext cdc = new MyDataContext())
{
List<orgUnit> queryOrgs = (
from p in cdc.orgUnits
select p
).ToList();
//Organizations
dropDownOrgs.DataSource = queryOrgs.ToList();
dropDownOrgs.DataValueField = "orgUnitID";
dropDownOrgs.DataTextField = "orgUnitName";
dropDownOrgs.DataBind();
}
}
}
精彩评论