Reading simple table using LinqDataSource. Table name is ZipCode with three columns: ZipCode, City, State). Read works fine with no filter, but when I add "Where" parameters to LinqDataSource, it fails in the GridView databind with an error, "No property or field "CityValue" exists in the type "ZipCode".
ASPX:
<asp:GridView ID="grdLDS" runat="server" AllowPaging="True" AllowSorting="True"
DataSourceID="ldsData" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="ZIPCODE1" HeaderText="ZipCode" SortExpression="ZIPCODE1" />
<asp:BoundField DataField="CITY" HeaderText="City" SortExpression="CITY" />
<asp:BoundField DataField="STATE" HeaderText="State" SortExpression="STATE" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="ldsData" runat="server" ContextTypeName="LinqLayer.CommonDataDataContext"
TableName="ZipCodes" OnSelecting="ldsData_Selecting" OnSelected="ldsData_Selected" >
</asp:LinqDataSource>
Code-Behind:
protected void ldsData_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if (!cbxLDS.Checked)
{
e.Cancel = true;
return;
}
ldsData.WhereParameters.Clear();
StringBuilder where = new StringBuilder();
if (!string.IsNullOrEmpty(txtFilterByZip.Text))
{
where.Append("ZIPCODE1.StartsWith(@ZipValue)");
ldsData.WhereParameters.Add("@ZipValue", txtFilterByZip.Text);
}
if (!string.IsNullOrEmpty(txtFilterByCity.Text))
{
if (where.Length > 0) where.Append(" & ");
where.Append("CITY.StartsWith(@CityValue)");
ldsData.WhereParameters.Add("@CityValue", txtFilterByCity.Text);
}
if (!string.IsNullOrEmpty(txtFilterByState.Text))
{
if (where.Length > 0) where.Append(" & ");
where.Append("STATE.StartsWith(@StateValue)");
ldsData.WhereParameters.Add("@StateValue", txtFilterByState.Text);
}
ldsData.Where = where.ToString();
}
protected void ldsData_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
LDSRowCount = e.TotalRowCount;
}
private int RefreshLDSData()
{
grdLDS.DataBind(); // <== CODE FAILS ON THIS LINE
return LDSRowCount;
}
private IEnumerable<ZipCode> FilterLDSData(IEnumerable<ZipCode> rows)
{
return rows;
}
Thanks to Andy Robinson, here is the solution:
lds_Data_Selecting event provides the structure of the query, and the ldsFilter method does the dynamic filtering. This method must accept and return an iQueryable.