asp gridview export to excel hide column - excel

Can someone please take a look at my code? this code works perfectly but i want to remove the 1st and 2nd column when the data exported to excel. i try GridView1.Columns[0].Visible = false; but its not working.
here's my aspx
<%# Page Title="VRQ" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="EmployeePage.aspx.cs" Inherits="EmployeePage"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('innerdata').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
function OpenFile(KEYW) {
window.open("ResumePage.aspx?bid=" + KEYW, "ResumeContext");
}
</script>
<asp:Button ID="btnbacksearch" runat="server" Text="Back to Search"
Width="127px" OnClick="btnbacksearch_Click" CssClass="plainbutton" />
<asp:Button ID="btnExportToExcel" runat="server" OnClick="btnExportToExcel_Click"
Text="Export Results to Excel" Width="174px" CssClass ="plainbutton" />
<asp:Button
ID="btnGenerateSF" runat="server" OnClick="btnGenerateSF_Click"
Text="Generate Resume" Width="137px" CssClass ="plainbutton"
Visible="False" />
<asp:DropDownList ID="ddStatus" runat="server"
onselectedindexchanged="ddStatus_SelectedIndexChanged" AutoPostBack="True"
Visible="False" Width="150px">
<asp:ListItem Selected="True" Value="Active">Active Personnel</asp:ListItem>
<asp:ListItem Value="Inactive">Inactive Personnel</asp:ListItem>
</asp:DropDownList>
<div style="font-size: 11pt; font-family: Tahoma; text-align:center "><strong>
SEARCH SUMMARY</strong></div>
<div style="font-size: 10pt; font-family: Tahoma; text-align:center ">
<asp:Label ID="LabelCaption" runat="server" Text="Label"></asp:Label>
</div>
<div id = "innerdata" style="size: landscape;" >
<asp:GridView ID="GridView1" runat="server"
CellPadding="4" DataSourceID="SqlDataSource1"
onrowcreated="GridView1_RowCreated"
AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
DataKeyNames="IDNo" AllowSorting="True" Width="100%"
PageSize="30" EmptyDataText="No Existing Records." CssClass="GridView"
onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False"
onsorted="GridView1_Sorted" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkSelect" Text="View" CommandName ="Select" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkPrintRep1" Text="Project Selection" CommandName ="PrintSF330" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="70px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="fullname" HeaderText="Name" ReadOnly="True"
SortExpression="fullname" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="YearsExperience" HeaderText="Experience"
SortExpression="YearsExperience" >
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Job" HeaderText="Position" SortExpression="Job" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Search Results" SortExpression ="SearchDetails">
<ItemTemplate>
<%# HighlightText(Convert.ToString(Eval("SearchDetails"))) %> </ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
<RowStyle CssClass="GridRowStyle"/>
<PagerStyle HorizontalAlign="Center" />
<SelectedRowStyle CssClass="GridSelected" />
<HeaderStyle CssClass="GridHeader" Height="10px" />
<PagerStyle CssClass="GridFooterStyle"/>
</asp:GridView></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HRIS_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:HRIS_ConnectionString.ProviderName %>"
SelectCommand="select i.IDNo,concat(lastname,', ',firstname,' ',middlename) as fullname,e.tYrsExperience as YearsExperience,p.Description as Job,'' as SearchDetails FROM employeesinfo i inner join ecd e on e.empid=i.idno
left outer join Position p on p.idno = e.presentjob">
</asp:SqlDataSource>
<vt:MessageBox ID="MessageBox1" runat="server"></vt:MessageBox>
</asp:Content>
and here's my aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
public partial class EmployeePage : System.Web.UI.Page
{
string sqry = ""; string scolumn = "";
string origQry = String.Empty;
public string keyword = "";
public string curAlpha = "";
public int iCtr = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["QRY_CONDITIONS"] == null) Response.Redirect("Default.aspx");
scolumn = Session["QRY_DETAIL"].ToString();
sqry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user == null) return;
if (user.IsSuperAdmin && sqry == "ALL")
{
ddStatus.Visible = true;
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") ;
}
else if(sqry == "ALL")
{
ddStatus.Visible = false;
sqry = " where ifnull(i.activestatus,0) = 1 ";
}
origQry = sqry;
if (Request.QueryString["keyword"] != null) keyword = Request.QueryString["keyword"].ToString().TrimEnd().TrimStart();
if (!IsPostBack)
{
if (keyword == "")
{
sqry = sqry + " and i.lastname like 'A%' ";
Session["QRY_alpha"] = " and i.lastname like 'A%' ";
curAlpha = "A";
}
LoadStates();
BindData();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
curAlpha = (string)ViewState["curAlpha"];
}
protected override object SaveViewState()
{
ViewState["curAlpha"] = curAlpha;
return base.SaveViewState();
}
private void BindData()
{
modPublic myMod = new modPublic();
SqlDataSource1.SelectCommand = "SELECT distinct i.idno,concat(i.lastname,', ',i.firstname,' ',i.middlename) as fullname,e.tYrsExperience as YearsExperience,e.Position as Job," + scolumn + " as SearchDetails FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + sqry + " order by i.lastname,i.firstname";
SqlDataSource1.Select(new DataSourceSelectArguments());
object o = myMod.ExecuteScalar("select count(distinct i.idno) as ctr FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + origQry + " ");
LabelCaption.Text = o.ToString() + " Record(s) found";
if (keyword == "")
{
GridView1.AllowPaging = false;
GridView1.Columns[5].Visible = false;
}
else
{
GridView1.Columns[5].Visible = true;
}
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AlphaPaging")
{
curAlpha = e.CommandArgument.ToString();
sqry = sqry + " and i.lastname like '" + e.CommandArgument + "%'";
Session["QRY_alpha"] = " and i.lastname like '" + e.CommandArgument + "%'";
GridView1.AllowPaging = false;
BindData();
SaveStates();
//this.SqlDataSource1.SelectCommand = "Select * from [Table_1] WHERE theName LIKE '" + e.CommandArgument + "%'";
}
if (e.CommandName == "PrintSF330")
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=" + e.CommandArgument.ToString() + " ");
}
else if (e.CommandName == "Select")
{
SaveStates();
loadECD(e.CommandArgument.ToString());
}
}
//protected override object SaveViewState()
//{
// ViewState["alphacond"] = alphacond;
// return base.SaveViewState();
//}
//protected override void LoadViewState(object savedState)
//{
// if (Page.IsPostBack)
// {
// base.LoadViewState(savedState);
// alphacond = ViewState["alphacond"].ToString();
// }
//}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// e.Row.Attributes.Add("OnClick", "javascript:" + Page.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
if (keyword == "")
{
if (e.Row.RowType == DataControlRowType.Footer)
{
GridViewRow grv = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
this.GridView1.Controls[0].Controls.Add(grv);
TableCell cell = new TableCell();
grv.Cells.Add(cell);
if (keyword == "")
cell.ColumnSpan = 5;
else
cell.ColumnSpan = 6;
for (int i = 65; i <= (65 + 25); i++)
{
string s = Char.ConvertFromUtf32(i);
if (s == curAlpha)
{
Label lt = new Label();
lt.Text = "[" + s + "]";
lt.Font.Bold = true;
lt.Font.Size = new FontUnit(12);
lt.Style["text-align"] = "middle";
cell.Controls.Add(lt);
}
else
{
LinkButton lb = new LinkButton();
lb.Text = s + " ";
lb.CommandArgument = s;
lb.CommandName = "AlphaPaging";
cell.Controls.Add(lb);
}
}
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
GridView1.Columns[0].Visible = false;
GridView1.AllowPaging = false;
BindData();
GridView1.DataBind();
GridViewExportUtil.Export("ReportResultsPage.xls", this.GridView1);
GridView1.AllowPaging = true;
BindData();
GridView1.Columns[0].Visible = false;
}
private void SaveStates()
{
if (Session["QRY_alpha"] == null) Session["QRY_alpha"] = "";
sqry = Session["QRY_CONDITIONS"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user.IsSuperAdmin && sqry == "ALL")
{
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") + Session["QRY_alpha"].ToString();
origQry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0");
}
else if (sqry == "ALL")
{
sqry = " where ifnull(i.activestatus,0) = 1 " + Session["QRY_alpha"].ToString();
origQry = " where ifnull(i.activestatus,0) = 1 ";
}
else
{
sqry = Session["QRY_CONDITIONS"].ToString() + Session["QRY_alpha"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
}
string tmp = "";
tmp = sqry + "|" +
scolumn + "|" +
keyword + "|" +
GridView1.SelectedIndex.ToString() + "|" +
GridView1.PageIndex.ToString() + "|" +
ddStatus.SelectedIndex.ToString() + "|" +
curAlpha + "|" +
origQry;
Session["PrevState"] = tmp;
}
public void LoadStates()
{
string tmp = (string)Session["PrevState"];
if (tmp == null)
{
return;
}
string[] arr = tmp.Split(new char[] { '|' });
sqry = arr[0];
scolumn = arr[1];
keyword = arr[2];
GridView1.SelectedIndex = Convert.ToInt32(arr[3]);
GridView1.PageIndex = Convert.ToInt32(arr[4]);
ddStatus.SelectedIndex = Convert.ToInt32(arr[5]);
curAlpha = arr[6];
origQry = arr[7];
}
void loadECD(string _idno)
{
SaveStates();
Response.Redirect("~/ECDMain.aspx?i=" + _idno);
}
protected void btnbacksearch_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
protected void btnGenerateSF_Click(object sender, EventArgs e)
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=ALL&EmpIDs=" + GetEmpID());
}
private string GetEmpID()
{
string temp = ""; string empIDs = "";
foreach (GridViewRow gRow in GridView1.Rows)
{
temp = GridView1.DataKeys[gRow.RowIndex].Value.ToString();
empIDs = (empIDs == "" ? empIDs : empIDs + ",") + temp;
}
return "(" + empIDs + ")";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && keyword !="")
e.Row.Cells[5].Text = e.Row.Cells[5].ToString().Replace(keyword,"<span style=//background-color: #FFFF00;//>" + keyword + "</span>");
}
public string HighlightText(string InputTxt)
{
// This function is called whenever text is displayed in the FirstName and LastName
// fields from our database. If we're not searching then just return the original
// input, this speeds things up a bit
if (string.IsNullOrEmpty(keyword))
{
return InputTxt;
}
else
{
// Otherwise create a new regular expression and evaluate the FirstName and
// LastName fields against our search string.
Regex ResultStr = default(Regex);
ResultStr = new Regex(keyword.Replace(" ", "|"), RegexOptions.IgnoreCase);
return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));
}
}
public string ReplaceWords(Match m)
{
// This match evaluator returns the found string and adds it a CSS class I defined
// as 'highlight'
return "<span class=highlight>" + m.ToString() + "</span>";
}
//protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
//{
// if ((e.Row.RowType == DataControlRowType.DataRow))
// {
// //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
// ((LinkButton)e.Row.FindControl("lnkResume")).Attributes.Add("onclick", "javascript:OpenFile('" + GridView1.DataKeys[e.Row.RowIndex].Value + "-" + keyword + "')");
// }
//}
protected void btnGenWord_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridViewExportUtil.ExportWord("ReportResultsPage.doc", this.GridView1);
GridView1.AllowPaging = true;
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
BindData();
}
protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e)
{
sqry = sqry + " and i.lastname like '" + curAlpha + "%'";
BindData();
}
}
Please can someone help me. Thanks in advance

You need to rebind the gridview after using the RemoveAt()
GridView1.Columns.RemoveAt(0);
GridView1.DataBind();

When user clicks on export to excel you can disable the delete button, export it and re-enable once exported
GridView1.AutoGenerateDeleteButton = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");

Related

How to show search results with their url's in Umbraco 7

I have implemented search in Umbraco 7 using examine and user control. Search is working fine. Now I need to show the URL of the search results displayed on the lists. Is there any index property like "BodyText" which can show the URL or do I have to do some stuff in user control?
User Control code:
public static class SiteSearchResultExtensions
{
public static string FullURL(this Examine.SearchResult sr)
{
return umbraco.library.NiceUrl(sr.Id);
}
}
public partial class SiteSearchResults : System.Web.UI.UserControl
{
#region Properties
private int _pageSize = 5;
public string PageSize
{
get { return _pageSize.ToString(); }
set
{
int pageSize;
if (int.TryParse(value, out pageSize))
{
_pageSize = pageSize;
}
else
{
_pageSize = 10;
}
}
}
private string SearchTerm
{
get
{
object o = this.ViewState["SearchTerm"];
if (o == null)
return "";
else
return o.ToString();
}
set
{
this.ViewState["SearchTerm"] = value;
}
}
protected IEnumerable<Examine.SearchResult> SearchResults
{
get;
private set;
}
#endregion
#region Events
protected override void OnLoad(EventArgs e)
{
try
{
CustomValidator.ErrorMessage = "";
if (!Page.IsPostBack)
{
topDataPager.PageSize = _pageSize;
bottomDataPager.PageSize = _pageSize;
string terms = Request.QueryString["s"];
if (!string.IsNullOrEmpty(terms))
{
SearchTerm = terms;
PerformSearch(terms);
}
}
base.OnLoad(e);
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
protected void searchResultsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
try
{
if (SearchTerm != "")
{
topDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
bottomDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
PerformSearch(SearchTerm);
}
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
#endregion
#region Methods
private void PerformSearch(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm)) return;
var criteria = ExamineManager.Instance
.SearchProviderCollection["ExternalSearcher"]
.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content);
// Find pages that contain our search text in either their nodeName or bodyText fields...
// but exclude any pages that have been hidden.
//var filter = criteria
// .GroupedOr(new string[] { "nodeName", "bodyText" }, searchTerm)
// .Not()
// .Field("umbracoNaviHide", "1")
// .Compile();
Examine.SearchCriteria.IBooleanOperation filter = null;
var searchKeywords = searchTerm.Split(' ');
int i = 0;
for (i = 0; i < searchKeywords.Length; i++)
{
if (filter == null)
{
filter = criteria.GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
else
{
filter = filter.Or().GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
}
//SearchResults = ExamineManager.Instance
// .SearchProviderCollection["ExternalSearcher"]
// .Search(filter);
SearchResults = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"].Search(filter.Compile());
if (SearchResults.Count() > 0)
{
searchResultsListView.DataSource = SearchResults.ToArray();
searchResultsListView.DataBind();
searchResultsListView.Visible = true;
bottomDataPager.Visible = topDataPager.Visible = (SearchResults.Count() > _pageSize);
}
summaryLiteral.Text = "<p>Your search for <b>" + searchTerm + "</b> returned <b>" + SearchResults.Count().ToString() + "</b> result(s)</p>";
// Output the query which an be useful for debugging.
queryLiteral.Text = criteria.ToString();
}
#endregion
}
}
I have done my Examine settings like this:
ExamineIndex.Config
<IndexSet SetName="ExternalndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/ExternalIndex/">
<IndexAttributeFields>
<add Name="id"/>
<add Name="nodeName"/>
<add Name="nodeTypeAlias"/>
<add Name="parentID" />
</IndexAttributeFields>
<IndexUserFields>
<add Name="bodyText"/>
<add Name="umbracoNaviHide"/>
</IndexUserFields>
<IncludeNodeTypes/>
<ExcludeNodeTypes/>
</IndexSet>
ExamineSettings.Config
ExamineIndexProviders
<add name="ExternalIndexer" type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
runAsync="true"
supportUnpublished="true"
supportProtected="true"
interval="10"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
ExamineSearchProvide
<add name="ExternalSearcher" type="UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
It was quite simple and i done some editing in the Usercontrol(SiteSearchresult.ascx)
like this
<li>
<a href="<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>">
<%# ((Examine.SearchResult)Container.DataItem).Fields["nodeName"] %>
<br >
addingvalue.webdevstaging.co.uk<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>
</a>
<p><%# ((Examine.SearchResult)Container.DataItem).Fields.ContainsKey("bodyText") == true ? ((Examine.SearchResult)Container.DataItem).Fields["bodyText"] : ""%></p>
</li>

Always getting error-"Object reference not set to an instance of an object."

I tried this way...so that when i click any menuitem in button1 it will check and check the same menuitem in the second button...but some where am getting error...I want to write it in better way .so that it will work as i need with out any issuse.here is the below code i did so far...how can i solve this issue as well as how can i improve this coding...
here is my code..
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" FlowDirection="LeftToRight">
<Button Name="btnPhone" Content="Business" Click="OnbtnPhoneClick" ></Button>
<Button Name="ddBtnPhone" Width="25" Click="OnddBtnPhoneClick" Height="47">
<Button.Content>
<Path x:Name="btnArrow1" Margin="4" VerticalAlignment="Center" Width="10" Fill="#FF527DB5" Stretch="Uniform" HorizontalAlignment="Right" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z "/>
</Button.Content>
<Button.ContextMenu>
<ContextMenu x:Name="cmPhone">
<MenuItem Header="Assistant " Name="mnIAssistant" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/> <MenuItem Header="Business" Name="mnIBusiness" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/> <MenuItem Header="Business 2 " Name="mnIBusiness2" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Business FAX " Name="mnIBusinessFAX" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Call Back" Name="mnICallback" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Car" Name="mnICar" Click="OnMenuItemChecked"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
<TextBox Height="19" Name="textBox1" Width="120" />
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" FlowDirection="LeftToRight">
<Button Name="btnHome" Content="Home" Click="OnbtnHomeClick" Height="26" Width="64" />
<Button Name="ddBtnHome" Width="25" Click="OnddBtnHomeClick" Margin="0,0,0,5" >
<Button.Content>
<Path x:Name="btnArrow2" Margin="4" VerticalAlignment="Center" Width="10" Fill="#FF527DB5" Stretch="Uniform" HorizontalAlignment="Right" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z "/>
</Button.Content>
<Button.ContextMenu>
<ContextMenu Name="cmHome">
<MenuItem Header="Assistant " Name="mnIAssistant1" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Business" Name="mnIBusiness1" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Business 2 " Name="mnIBusiness21" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Business FAX " Name="mnIBusinessFAX1" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Call Back" Name="mnICallback1" Checked="OnMenuItemChecked" Click="OnMenuItemClick"/>
<MenuItem Header="Car" Name="mnICar1" Click="OnMenuItemChecked"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
<TextBox Height="23" Name="textBox2" Width="120" />
</StackPanel>
<Border Grid.Row="3" BorderThickness="2" BorderBrush="Blue">
<TextBlock Name="tbWebpage" Grid.Row="3" Background="White" VerticalAlignment="Top" Height="20">
<Hyperlink NavigateUri="tbWebpage.Text" RequestNavigate="Hyperlink_RequestNavigate"></Hyperlink>
</TextBlock>
</Border>
</Grid>
code behind xaml
namespace MenuItemsChecked
{
public partial class MainWindow : Window
{
//string[] arrMenitems = { "business", "a1", "a2", "a3","a4" };
Button btnCommon = new Button();
TextBox txtCommon = new TextBox();
MenuItem mnItem;
public MainWindow()
{
InitializeComponent();
}
private void AddMenuItems(ContextMenu cMenu, Button btnName, TextBox txtBoxName)
{
//mnItem.Items.Add(arrMenitems);
if (cMenu.Items.Count != 0)
{
//mnItem = new MenuItem();
//mnItem.Header = "Business";
//mnItem.IsCheckable = true;
//cMenu.Items.Add(mnItem);
//mnItem = new MenuItem();
//mnItem.Header = "Assistant";
//mnItem.IsCheckable = true;
//cMenu.Items.Add(mnItem);
//mnItem = new MenuItem();
//mnItem.Header = "Business 2";
//mnItem.IsCheckable = true;
//cMenu.Items.Add(mnItem);
//mnItem = new MenuItem();
//mnItem.Header = "Business FAX";
//mnItem.IsCheckable = true;
//cMenu.Items.Add(mnItem);
//mnItem = new MenuItem();
//mnItem.Header = "Call Back";
//mnItem.IsCheckable = true;
//cMenu.Items.Add(mnItem);
//cMenu.Items.Add(mnItem);
//cmCommon = cMenu;
cMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
cMenu.AddHandler(MenuItem.MouseLeftButtonUpEvent, new MouseButtonEventHandler(OnMouseButtonUpEventClick));
// cMenu.AddHandler(MenuItem.CheckedEvent, new RoutedEventHandler(OnMenuItemChecked));
btnCommon = btnName;
//txtCommon = txtBoxName;
}
}
private void OnMenuItemChecked(object sender, RoutedEventArgs e)
{
RoutedEventArgs args = e as RoutedEventArgs;
MenuItem item = args.OriginalSource as MenuItem;
if (sender == mnIAssistant)
{
mnIAssistant.IsChecked = true;
mnIAssistant1.IsChecked = true;
}
if (sender == mnIBusiness)
{
mnIBusiness.IsChecked = true;
mnIBusiness1.IsChecked = true;
}
if (sender == mnIBusiness2)
{
mnIBusiness2.IsChecked = true;
mnIBusiness21.IsChecked = true;
}
if (sender == mnIBusinessFAX)
{
mnIBusinessFAX.IsChecked = true;
mnIBusinessFAX1.IsChecked = true;
}
if (sender == mnICallback)
{
mnICallback.IsChecked = true;
mnICallback1.IsChecked = true;
}
if (sender == mnICar)
{
mnICar.IsChecked = true;
mnICar1.IsChecked = true;
}
if (sender == mnIAssistant1)
{
mnIAssistant.IsChecked = true;
mnIAssistant1.IsChecked = true;
}
if (sender == mnIBusiness1)
{
mnIBusiness.IsChecked = true;
mnIBusiness1.IsChecked = true;
}
if (sender == mnIBusiness21)
{
mnIBusiness2.IsChecked = true;
mnIBusiness21.IsChecked = true;
}
if (sender == mnIBusinessFAX1)
{
mnIBusinessFAX.IsChecked = true;
mnIBusinessFAX1.IsChecked = true;
}
if (sender == mnICallback1)
{
mnICallback.IsChecked = true;
mnICallback1.IsChecked = true;
}
if (sender == mnICar1)
{
mnICar.IsChecked = true;
mnICar1.IsChecked = true;
}
}
private void OnMouseButtonUpEventClick(object sender, MouseButtonEventArgs e)
{
(sender as MenuItem).IsChecked = !(sender as MenuItem).IsChecked;
((sender as MenuItem).Parent as ContextMenu).IsOpen = false;
}
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
RoutedEventArgs args = e as RoutedEventArgs;
// MenuItem item = args.OriginalSource as MenuItem;
//string header = item.Header.ToString();
MenuItem menuitem = sender as MenuItem; ///always getting error-"Object reference not set to an instance of an object."
//ContextMenu cm = sender as ContextMenu;
string name = menuitem.Name;
string header = menuitem.Header.ToString();
if ((sender == mnIBusiness) |(sender == mnIBusiness1))
{
if (header == "Business")
{
mnIBusiness.IsChecked = true;
mnIBusiness1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsCheckable = true;
}
else if ((sender == mnIAssistant) | (sender == mnIAssistant1))
{
if (header == "Assistant")
{
mnIAssistant.IsChecked = true;
mnIAssistant1.IsChecked = true;
}
btnCommon.Content = header;
///item.IsChecked = true;
}
else if ((sender == mnIBusiness2) | (sender == mnIBusiness21))
{
//if(header=="Business 2")
//{
mnIBusiness2.IsChecked = true;
mnIBusiness21.IsChecked = true;
//}
btnCommon.Content = header;
//item.IsChecked = true;
}
else if ((sender == mnIBusinessFAX) |(sender == mnIBusinessFAX1))
{
if(header=="Business FAX")
{
mnIBusinessFAX.IsChecked = true;
mnIBusinessFAX1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsChecked = true;
}
else if ((sender == mnICallback1) | (sender == mnICallback))
{
if (header == "Call Back")
{
mnICallback.IsChecked = true;
mnICallback1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsChecked = true;
}
else
{
if (header == "Car")
{
mnICar.IsChecked = true;
mnICar1.IsChecked = true;
}
btnCommon.Content = header;
}
txtCommon.Text = string.Empty;
}
private void OnddBtnPhoneClick(object sender, RoutedEventArgs e)
{
ButtonContextMenuDisplay(sender);
AddMenuItems(cmPhone, btnPhone, textBox1);
}
private void OnbtnPhoneClick(object sender, RoutedEventArgs e)
{
}
private void OnbtnHomeClick(object sender, RoutedEventArgs e)
{
}
private void OnddBtnHomeClick(object sender, RoutedEventArgs e)
{
ButtonContextMenuDisplay(sender);
AddMenuItems(cmHome, btnHome, textBox2);
}
private void ButtonContextMenuDisplay(object sender)
{
(sender as Button).ContextMenu.IsEnabled = true;
(sender as Button).ContextMenu.PlacementTarget = (sender as Button);
(sender as Button).ContextMenu.IsOpen = true;
(sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
}
}
}
hey kida somehow your onmenuitemclick is being called more than one time and it is working well for first time but when it is called again then menuitem becomes null so it giving you nullreference exception i have put a small check..to make it work..so check it out..
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
RoutedEventArgs args = e as RoutedEventArgs;
// MenuItem item = args.OriginalSource as MenuItem;
//string header = item.Header.ToString();
MenuItem menuitem = sender as MenuItem; ///always getting error-"Object reference not set to an instance of an object."
if (menuitem != null)
{
ContextMenu cm = sender as ContextMenu;
// string name = menuitem.Name;
string header = menuitem.Header.ToString();
if ((sender == mnIBusiness) | (sender == mnIBusiness1))
{
if (header == "Business")
{
mnIBusiness.IsChecked = true;
mnIBusiness1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsCheckable = true;
}
else if ((sender == mnIAssistant) | (sender == mnIAssistant1))
{
if (header == "Assistant")
{
mnIAssistant.IsChecked = true;
mnIAssistant1.IsChecked = true;
}
btnCommon.Content = header;
///item.IsChecked = true;
}
else if ((sender == mnIBusiness2) | (sender == mnIBusiness21))
{
//if(header=="Business 2")
//{
mnIBusiness2.IsChecked = true;
mnIBusiness21.IsChecked = true;
//}
btnCommon.Content = header;
//item.IsChecked = true;
}
else if ((sender == mnIBusinessFAX) | (sender == mnIBusinessFAX1))
{
if (header == "Business FAX")
{
mnIBusinessFAX.IsChecked = true;
mnIBusinessFAX1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsChecked = true;
}
else if ((sender == mnICallback1) | (sender == mnICallback))
{
if (header == "Call Back")
{
mnICallback.IsChecked = true;
mnICallback1.IsChecked = true;
}
btnCommon.Content = header;
//item.IsChecked = true;
}
else
{
if (header == "Car")
{
mnICar.IsChecked = true;
mnICar1.IsChecked = true;
}
btnCommon.Content = header;
}
txtCommon.Text = string.Empty;
}
}
post your query in comments..

How to call SP.UI.Status in visual webpart

I have a scenario where i need to display an Alert banner with the title column in my list.
Below is the code which iam trying to use . But it is not displaying correctly. Can any one let me know Errorl
<script type="text/ecmascript" language="ecmascript">
var strStatusID;
function showInfo(strMessage) {
alert("Code sucess");
strStatusID = SP.UI.Status.addStatus(strMessage, true);
alert(strMessage.toString());
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
</script>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblScripter" runat="server" Visible="false"></asp:Label>
</asp:Panel>
public void LoadGrid()
{
//System.Diagnostics.Debugger.Break();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
}
// strStatusID = SP.UI.Status.addStatus(strMessage, true);
lblScripter.Text = "<Script language='javascript;>showInfo('" + MessageShow + "');</script>";
}
else
{
lblScripter.Visible = false;
}
}
<asp:Timer runat="server" ID="UpdateTimer" Interval="6000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Alertlist"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
Enddate = DateTime.Parse(item["EndDate"].ToString());
}
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>";
if (Currenttime >= Enddate)
{
lblScripter.Text = "hi after date tim refreshed";
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {removeAllInfos();}, 'sp.js');</script>";
}
}
//else
//{
// lblScripter.Visible = false;
//}
}
Try to set :
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>"
Most likely this will solve your problem of calling the SP.UI.Status javascript functions before they have been loaded.
I Have solved this PFB code in order to acheive this. Thanks to my friend Hameed who has helped me to acheive the same
<script type="text/ecmascript" language="ecmascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RegisterMethods);
function RegisterMethods() {
showInfo();
RemoveLastStatus();
}
function showInfo() {
var strMessage = document.getElementById('<%= Message.ClientID %>').value;
var strstatus = document.getElementById('<%= StartStatus.ClientID %>').value;
if (strMessage != null) {
if (strstatus != "false") {
var strStatusID;
strStatusID = SP.UI.Status.addStatus(strMessage);
SP.UI.Status.setStatusPriColor(strStatusID, "red");
document.getElementById('<%= StartStatus.ClientID %>').value = "false";
document.getElementById('<%= StatusId.ClientID %>').value = strStatusID;
}
}
}
function RemoveLastStatus() {
var statusId = document.getElementById('<%= StatusId.ClientID %>').value;
var stopStatus = document.getElementById('<%= StopStatus.ClientID %>').value;
if (statusId != null) {
if (stopStatus == "true") {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
}
}
</script>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server" Visible="True"></asp:Label>
<asp:HiddenField ID="StartStatus" runat="server" />
<asp:HiddenField ID="StopStatus" runat="server" />
<asp:HiddenField ID="Message" runat="server" />
<asp:HiddenField ID="StatusId" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
CODEBEHIND.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Globalization;
using System.Data;
using System.Linq;
using Microsoft.SharePoint.Utilities;
namespace ITBANNER
{
public partial class ITOpsBannerUserControl : UserControl
{
String MessageShow = string.Empty;
DateTime Enddate, starttime;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItemCollection items = oSpList.Items;
SPListItem item;
for (int i = 0; i < items.Count; i++)
{
item = items[i];
Console.WriteLine("Index = {0} ID = {1}", i, item.ID);
}
SPListItem item = oSpList.GetItemById(3);
Message.Value = item["Title"].ToString();
starttime = DateTime.Parse(item["StartDate"].ToString());
if (Currenttime >= starttime)
{
StartStatus.Value = "true";
StopStatus.Value = "false";
}
}
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItem item = oSpList.GetItemById(3);
Enddate = DateTime.Parse(item["EndDate"].ToString());
if (Currenttime >= Enddate)
{
StopStatus.Value = "true";
}
}
//public void HideStatusBar()
//{
// string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
// this.Page.ClientScript.RegisterClientScriptBlock(typeof(Type), "statusBarRemover", script, true);
//}
}
}

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

Filter a SharePoint list by audience

I am very new to Sharepoint development. I have the following code that I need to have display the list items by targeted audience. I know I am suppose to add something like this
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in list.Items)
{
// get roles the list item is targeted to
string audienceFieldValue = (string)listItem[k_AudienceColumn];
// quickly check if the user belongs to any of those roles
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader,
audienceFieldValue,
false))
But I have no idea where to place it in my code below. Please I would appreciate any of your advise.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
namespace PersonalAnnouncements.PersonalAnnouncements
{
[ToolboxItem(false)]
public class PersonalAnnouncements : Microsoft.SharePoint.WebPartPages.WebPart
{
// Fields
private string _exceptions = "";
private AddInsEnum DE = AddInsEnum.HyperLink;
private const AddInsEnum DefaultAddInsEnum = AddInsEnum.HyperLink;
private const TheDateFormat DefaultDateFormat = TheDateFormat.MonthDayYear;
private const PeriodEnum DefaultPeriod = PeriodEnum.Five;
private const string defaultText = "Your text here";
private const string DefaultURL = "DispForm.aspx";
private TheDateFormat DF = TheDateFormat.MonthDayYear;
private string endField = "Image URL";
private const string imgTURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private const string imgURL = "/_layouts/NewsViewer/banner1.jpg";
protected Label lblError;
private const string listText = "";
private string listViewFields = "";
private PeriodEnum Period = PeriodEnum.Five;
private string sImageURL = "/_layouts/NewsViewer/banner1.jpg";
private string siteURLtext = "Your Site here";
private string startField = "Body";
private string sTImageURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private string sTimeField = "/_layouts/NewsViewer/style_smaller.css";
private string sYAxisTitle = "15";
private string text = "Your text here";
private string ThumbImageField = "";
private const string timer = "/_layouts/NewsViewer/style_smaller.css";
private string titleField = "";
private string urltocalendar = "DispForm.aspx";
private const string yaxistit = "15";
// Methods
protected override void CreateChildControls()
{
HtmlTable table;
HtmlTableRow row;
HtmlTableCell cell;
bool controlsAdded = false;
try
{
base.CreateChildControls();
SPWeb theWeb = new SPSite(this.SiteURL).OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(theWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[this.Text];
if (list.BaseTemplate == SPListTemplateType.GenericList)
{
this.lblError = new Label();
this.lblError.Text = "Error:";
this.lblError.Visible = true;
HtmlTable child = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
string str = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.CSSField + "\" /><script type=\"text/javascript\" src=\"/_layouts/NewsViewer/jquery-1.3.2.min.js\"></script><script type=\"text/javascript\">var X = jQuery.noConflict();X(document).ready(function() {\t X(\".main_image .desc\").show(); X(\".main_image .block\").animate({ opacity: 0.85 }, 1 ); X(\".image_thumb ul li:first\").addClass('active'); X(\".image_thumb ul li\").click(function(){ var imgAlt = X(this).find('img').attr(\"alt\"); var imgTitle = X(this).find('a').attr(\"href\"); var imgDesc = X(this).find('.block').html(); \t var imgDescHeight = X(\".main_image\").find('.block').height();\t\t if (X(this).is(\".active\")) { return false; } else { X(\".main_image .block\").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { X(\".main_image .block\").html(imgDesc).animate({ opacity: 0.85,\tmarginBottom: \"0\" }, 250 ); X(\".main_image img\").attr({ src: imgTitle , alt: imgAlt}); }); } X(\".image_thumb ul li\").removeClass('active'); X(this).addClass('active'); return false;}) .hover(function(){ X(this).addClass('hover'); }, function() { X(this).removeClass('hover');}); X(\"a.collapse\").click(function(){ X(\".main_image .block\").slideToggle(); X(\"a.collapse\").toggleClass(\"show\"); });}); </script><div id=\"main\" class=\"container\">";
string sideNav = this.GetSideNav();
string mainContent = this.GetMainContent();
cell.InnerHtml = str + mainContent + sideNav + "</div></div>";
row.Cells.Add(cell);
child.Rows.Add(row);
this.Controls.Add(child);
controlsAdded = true;
}
}
}
});
}
catch (Exception exception)
{
if (controlsAdded)
{
this._exceptions = this._exceptions + "CreateChildControls_Exception: " + exception.Message;
}
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Error: " + exception.Message;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
}
if (!controlsAdded)
{
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Please choose the Personal Announcement list: " + this.Text + " - Site:" + this.SiteURL;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
else
{
cell.InnerHtml = "Please setup Personal Announcement by clicking Modify Shared WebPart";
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
}
}
private string FirstWords(string input, int numberWords)
{
try
{
int num = numberWords;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ' ')
{
num--;
}
if (num == 0)
{
return input.Substring(0, i);
}
}
}
catch (Exception)
{
}
return string.Empty;
}
private string GetMainContent()
{
string str = "";
this.lblError.Text = this.lblError.Text + " -> GetMainContent()";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
view.RowLimit = 1;
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num == 0)
{
object obj2;
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
str2 = str2 + "<div class=\"main_image\">";
str2 = str2 + "<img src=\"" + imageURL + "\" alt=\"BNNewsbanner\" />";
str2 = str2 + "<div class=\"desc\" >Close Me!";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No Title Text Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
// str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
}
num++;
}
}
str = str + str2;
}
}
return str;
}
public int getNumber(string number)
{
switch (number)
{
case "One":
return 1;
case "Two":
return 2;
case "Three":
return 3;
case "Four":
return 4;
case "Five":
return 5;
case "Six":
return 6;
case "Seven":
return 7;
case "Eight":
return 8;
case "Nine":
return 9;
case "Ten":
return 10;
}
return 0;
}
private string GetSideNav()
{
this.lblError.Text = this.lblError.Text + " -> GetSideNav()";
string str = "<div class=\"image_thumb\"><ul>";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num < num2)
{
object obj2;
string imageThumbURL = "";
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
if (item[this.ThumbImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString();
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else
{
imageThumbURL = this.ImageThumbURL;
}
str2 = str2 + "<li><a href=\"" + imageURL + "\">";
str2 = str2 + "<img src=\"" + imageThumbURL + "\" alt=\"\" /></a>";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No List Title Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
}
num++;
}
}
str = str + str2;
}
}
return (str + "</ul>");
}
public override ToolPart[] GetToolParts()
{
ToolPart[] partArray = new ToolPart[3];
WebPartToolPart part = new WebPartToolPart();
CustomPropertyToolPart part2 = new CustomPropertyToolPart();
partArray[0] = part2;
partArray[1] = part;
partArray[2] = new CustomToolPart();
return partArray;
}
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception exception)
{
this._exceptions = this._exceptions + "RenderContents_Exception: " + exception.Message;
}
finally
{
if (this._exceptions.Length > 0)
{
writer.WriteLine(this._exceptions);
}
}
}
private string StripTagsCharArray(string source)
{
char[] chArray = new char[source.Length];
int index = 0;
bool flag = false;
for (int i = 0; i < source.Length; i++)
{
char ch = source[i];
if (ch == '<')
{
flag = true;
}
else if (ch == '>')
{
flag = false;
}
else if (!flag)
{
chArray[index] = ch;
index++;
}
}
return new string(chArray, 0, index);
}
// Properties
public string BodyField
{
get
{
return this.startField;
}
set
{
this.startField = value;
}
}
[WebDisplayName("Style Sheet URL"), WebDescription("Specifies the path to the css file"), SPWebCategoryName("General Settings"), Personalizable(true), WebBrowsable(true)]
public string CSSField
{
get
{
return this.sTimeField;
}
set
{
this.sTimeField = value;
}
}
[WebBrowsable(true), Personalizable(true), WebDisplayName("Date Format"), WebDescription("Date Format of your News Items"), SPWebCategoryName("General Settings")]
public TheDateFormat DateFormat
{
get
{
return this.DF;
}
set
{
this.DF = value;
}
}
[WebBrowsable(true), WebDescription("Thumb Image URL to use when no image is found"), SPWebCategoryName("General Settings"), Personalizable(true), WebDisplayName("No Thumb Image URL")]
public string ImageThumbURL
{
get
{
return this.sTImageURL;
}
set
{
this.sTImageURL = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebBrowsable(true), WebDisplayName("No Image URL"), WebDescription("Image URL to use when no image is found")]
public string ImageURL
{
get
{
return this.sImageURL;
}
set
{
this.sImageURL = value;
}
}
public string ImageURLField
{
get
{
return this.endField;
}
set
{
this.endField = value;
}
}
public string ListViewFields
{
get
{
return this.listViewFields;
}
set
{
this.listViewFields = value;
}
}
[WebDescription("Number of news items to show"), WebDisplayName("Number of news items to show"), WebBrowsable(true), SPWebCategoryName("General Settings"), Personalizable(true)]
public PeriodEnum NumEvents
{
get
{
return this.Period;
}
set
{
this.Period = value;
}
}
[WebDisplayName("Number of words to show from the Body"), Personalizable(true), SPWebCategoryName("General Settings"), WebDescription("Specifies the number of words to show from the body in the main webpart, under the Title"), WebBrowsable(true)]
public string NumWords
{
get
{
return this.sYAxisTitle;
}
set
{
this.sYAxisTitle = value;
}
}
public string SiteURL
{
get
{
return this.siteURLtext;
}
set
{
this.siteURLtext = value;
}
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebDisplayName("Image Column Type")
You can put the code in CreateChildControls() method.

Resources