SharePoint's ListViewWebPart --- Part 2
In continuation with previous post SharePoint's ListViewWebPart.
In this post I discussed how we can apply complex filter in SharePoint's ListView WebPart.
In one of appliation I was using SharePoint's ListView webpart in an aspx page to display the records from SPList. In that page I am also providing a search funtionality. Based on the applied search I am changing the records displayed in ListView webpart.
So the challenge was to apply the complex search filter on ListView webpart programmatically and dynamically. ListView webpart exposes FilterString property but in that we can apply simple filter and that only to one column (as per my knowledge).
So to apply complex filter, first we have to get the SPView from which we are populating data in ListViewWebPart. Then change the Query property of SPView as per our requirement.
In following method I implemented the above mentioned logic (codes with comments are self-explainatory).
/// <summary>
/// Search functionality OR Apply complex filter in SharePoint's ListView WebPart
/// </summary>
/// <param name="eventArgument"></param>
void searchRecord(string flag)
{
try
{
SPSite oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["LISTNAME"];
//oListViewWP is ListView Webpart's ID
oWebsite.AllowUnsafeUpdates = true;
//Clear Search filter OR revert back SPView modification.
if (flag == "false")
{
//Listview webpart related settings
oListViewWP.ListName = oList.ID.ToString("B").ToUpper();
//Set SPView for Listview WP
SPView view = oList.Views["SPView_NAME"];
view.Query = string.Empty;
view.Update();
oListViewWP.ViewGuid = view.ID.ToString("B").ToUpper();
oListViewWP.GetDesignTimeHtml();
}
else
{
//Build the SPQuery
StringBuilder strbPreQuery
= new StringBuilder("<Where><Contains>");
StringBuilder strbPostQuery
= new StringBuilder("</Value></Contains></Where>");
string strQueryKeyword = string.Empty;
switch (drpSearchKeywordType.SelectedValue)
{
case "Contact Number":
strQueryKeyword
= "<FieldRef Name='Contact_x0020_Number'/>
<Value Type='Text'>";
break;
case "Email ID":
strQueryKeyword
= "<FieldRef Name='Email_x0020_ID'/>
<Value Type='Text'>";
break;
}
//Build SPQuery
SPQuery oQuery = new SPQuery();
oQuery.Query
= strbPreQuery.ToString() + strQueryKeyword +
txtSearchKeyword.Text + strbPostQuery.ToString();
SPListItemCollection itemCol = oWebsite.Lists[spListName].GetItems(oQuery);
if (itemCol.Count > 0)
{
//Listview webpart related settings
oListViewWP.ListName = oList.ID.ToString("B").ToUpper();
//Modifying SPView as per required SPQuery.
SPView view = oList.Views["SPView_NAME"];
view.Query = oQuery.Query;
view.Update();
//Modifying ListView WebPart as changed SPView
oListViewWP.ViewGuid = view.ID.ToString("B").ToUpper();
oListViewWP.GetDesignTimeHtml();
}
}
oWebsite.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
}
}
