CS0103: The name **** does not exist in the current context - c#

The code worked before I did nothing other than added another variable and a getter to it.
Now everything doesn't work.
The .NET version of all the projects in the solution is the same (4.7).
Screenshot of the error
I cannot run the project anymore as it doesn't start properly (there's an error).
What is going on? This has been happening for months now. The answer I got from my seniors is that it's a matter of the solution being that huge that Visual Studio mishandles it occassionally and thus this error is the resulting mishap. The difference is that this time, restarting Visual Studio/my computer didn't "solve" it. I tried with those restarts after cleaning and rebuilding didn't achieve anything.
Does anyone know what to do?
The code worked before I added <%# GetCssClass %> to the .ascx file. After I added that, everything became broken, and even when I undo adding that, nothing still works.
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="EventICTGenerator.ascx.cs" Inherits="CMSApp.CMSWebParts.MyCompany.DetailPages.Event.EventICTGenerator" %>
<%# Register Src="~/CMSWebParts/MyCompany/Controls/ICSCalendarControl.ascx" TagPrefix="uc1" TagName="ICSCalendarControl" %>
<uc1:ICSCalendarControl runat="server" ID="ICSCalendarControl" LinkCssClass='event-header__info-actions-save <%# GetCssClass %>'
ResourceString="MyCompany.event.SaveTheDate"
EventName='<%# EventName %>'
EventLocation='<%# EventLocation %>'
EventAddress='<%# EventAddress %>'
EventStartDate='<%# EventStartDate %>'
EventEndDate='<%# EventEndDate %>'
EventSummary='<%# EventSummary %>' />
<%# Position %>
.ascx.cs
using CMS.DocumentEngine;
using CMS.Helpers;
using CMS.PortalEngine.Web.UI;
using System;
using System.Linq;
namespace CMSApp.CMSWebParts.MyCompany.DetailPages.Event
{
public partial class EventICTGenerator : CMSAbstractWebPart
{
protected string EventName = "";
protected string EventLocation = "";
protected string EventAddress = "";
protected DateTime EventStartDate = DateTime.Now;
protected DateTime EventEndDate = DateTime.Now;
protected string EventSummary = "";
protected int widgetPosition = -1;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!StopProcessing)
{
SetupControl();
BindEventData(EventDocumentID);
}
}
private void SetupControl()
{
BindEventData(EventDocumentID);
this.DataBind();
widgetPosition = Position;
}
protected string EventDocumentID
{
get
{
return ValidationHelper.GetString(GetValue("EventID"), string.Empty);
}
}
protected string EventLink
{
get
{
return ValidationHelper.GetString(GetValue("Link"), string.Empty);
}
}
protected int Position
{
get
{
return ValidationHelper.GetInteger(GetValue("Position"), -1);
}
}
protected string GetCssClass
{
get
{
return Position switch
{
1 => "generic-content_align generic-content_align–left",
2 => "generic-content_align generic-content_align–center",
3 => "generic-content_align generic-content_align–right",
_ => "",
};
}
}
protected string EventLinkText
{
get
{
return ValidationHelper.GetString(GetValue("LinkText"), string.Empty);
}
}
private string LinkTextAndUrl()
{
return $"{EventLinkText} <{EventLink}>";
}
private void BindEventData(string documentID)
{
TreeNode item = DocumentHelper.GetDocuments("MyCompany.Event")
.Columns("EventName, LocationName, LocationAddress, ShortDescription, Date, EndDate")
.OnCurrentSite()
.WhereEquals("DocumentID", documentID)
.FirstOrDefault();
if (item != null)
{
string summary = ValidationHelper.GetString(item.GetValue("ShortDescription"), string.Empty);
this.EventName = ValidationHelper.GetString(item.GetValue("EventName"), string.Empty);
this.EventLocation = ValidationHelper.GetString(item.GetValue("LocationName"), string.Empty);
this.EventAddress = ValidationHelper.GetString(item.GetValue("LocationAddress"), string.Empty);
this.EventSummary = $"{summary}\n{LinkTextAndUrl()}";
this.EventStartDate = ValidationHelper.GetDateTime(item.GetValue("Date"), DateTime.Now);
this.EventEndDate = ValidationHelper.GetDateTime(item.GetValue("EndDate"), DateTime.Now);
}
}
}
}

What "solved" was this changing my switch-case.
I inputted it like
switch
{
1 => "generic-content_align generic-content_align–left",
2 => "generic-content_align generic-content_align–center",
3 => "generic-content_align generic-content_align–right",
_ => "",
};
VS was telling me that my switch case was not good, and that's why I changed it to that form to begin with. It then didn't tell me anything's wrong with it or in any way point me to it. -.-
Now that I've changed the way that that switch case is writtern voila, it works.

Related

why can't i access a function of a web control?

i have the next question:
I've got an .aspx which contains a lot of web controls, this is the one i care:
//line 5
<%# Register src="Controls/UCAttachments.ascx" tagname="UCAttachments" tagprefix="uc1" %>
//line 430
<uc1:UCAttachments ID="UCAttachments" runat="server" Visible="false" />
On the selected index changed event of a combo box, i need to call a function of the web control, this is the code of the .aspx.cs.
private void cbo_SelectedIndexChanged( object sender, EventArgs e )
{
if(this.op == 1){
UCAttachments.visible=true;
UCAttachments.loadById(this.id); <-this doesnt work.
//Even tho, i can access all the other functions of UCAttachments.
//More infor abkout the error:
//'CONTROL' does not contain a definition for 'loadById'and no accessible //method accepting first argument...
}
}
public partial class Controls_UCAttachments: System.Web.UI.UserControl
{
//lots of functions
public void loadById( string id )
{
string query = "SELECT * FROM table WHERE ID = " +id;
//more code
return ;
}
}
you have to make this method static
public partial class Controls_UCAttachments
{
//lots of functions
static public void loadById(string id)
{
string query = "SELECT * FROM table WHERE ID = " + id;
//more code
return;
}
}
and you can call using this syntax
Controls_UCAttachments.loadById(this.id);
so.. very curious thing.
when you have a form which contains a lot of user controls, you need to wait for the metadata file to reload the new methods you've created.
So i closed my visual studio and re opeened a minutes later and the bug desapeared.

Not able to read checked status of Custom Checkbox Server Control

I am not able to read the Checked status of my custom checkbox control.
I created this control so that it would rendor correctly for easy use with bootstrap.
The control renders perfectly, and I have all the function that I want/need EXCEPT being able to read the checked status of the input when the user clicks 'submit'.
Custom Server Control Code (C#):
public class InlineBootstrapCheckBox : CheckBox, IPostBackDataHandler, ICheckBoxControl
{
private string value;
private string labelCSS;
private string labelID;
public string LabelID
{
get
{
if (!string.IsNullOrEmpty(this.labelID))
{
return this.labelID;
}
else
{
return null;
}
}
set
{
this.labelID = value;
}
}
public string LabelCSS
{
get
{
if (!string.IsNullOrEmpty(this.labelCSS))
{
return this.labelCSS;
}
else
{
return null;
}
}
set
{
this.labelCSS = value;
}
}
public string Value
{
get
{
if (!string.IsNullOrEmpty(this.value))
{
return this.value;
}
else
{
throw new NotImplementedException("You must set a 'Value' for InlineBootstrapCheckBox Controls");
}
}
set
{
this.value = value;
}
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.WriteLine(string.Format("<label id=\"{0}\" class=\"{1}\" for=\"{2}\">", (this.LabelID != null) ? this.LabelID : string.Concat(this.ID, "_Label"), (this.LabelCSS != null) ? string.Concat(this.LabelCSS, " checkbox-inline") : "checkbox-inline", this.ID));
writer.WriteLine(string.Format("<input type=\"checkbox\" id=\"{0}\" value=\"{1}\">", this.ID, this.Value));
writer.WriteLine(this.Text);
writer.WriteLine("</label>");
}
}
Markup Code (.ASPX):
<div class="form-group">
<label id="lblCategories" class="col-sm-3 control-label">Categories</label>
<div class="col-sm-9">
<cookout:InlineBootstrapCheckBox runat="server" ID="chkRibs" Text="Ribs" Value="1" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkChicken" Text="Chicken" Value="2" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkBrisket" Text="Beef Brisket" Value="3" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkPork" Text="Pork" Value="4" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkAnythingBut" Text="Anything But" Value="5" />
</div>
</div>
Code Behind (C#):
This is where I think my problem is?
protected void btnSubmit_Click(object sender, EventArgs e)
{
ProRegistration regInfo = new ProRegistration();
regInfo.TeamName = this.txtTeamName.Text.ToString();
regInfo.ContactName = this.txtContactName.Text.ToString();
regInfo.StreetAddress = this.txtContactAddress.Text.ToString();
regInfo.City = this.txtContactCity.Text.ToString();
regInfo.State = this.txtContactState.Text.ToString();
regInfo.ZipCode = this.txtContactZip.Text.ToString();
regInfo.Email = this.txtContactEmail.Text.ToString();
regInfo.Phone = this.txtContactPhone.Text.ToString();
regInfo.IsRibs = this.chkRibs.Checked;
regInfo.IsChicken = this.chkChicken.Checked;
regInfo.IsBrisket = this.chkBrisket.Checked;
regInfo.IsPork = this.chkPork.Checked;
regInfo.IsAnythingBut = this.chkAnythingBut.Checked;
regInfo.Created = DateTime.Now;
DataManager.InsertProfessionalRegistration(regInfo);
}
...So basically what I need is to be able to get a positive response when I try to submit this object to my database. Currently, no matter the click status, I get a false result.
I have been trying to research an answer to this for about 3 hours now to no avail.
Thank you!
I don't know bootstrap but it looks like you are injecting an html checkbox into the output. If this is the case it will not be recognized as a server control on postback, however you can get its value by using the request.form object.
string result=Request.Form["thecheckboxid"];

javascript open modal window return values,, i dont get it?

I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.

Register which anchor tag made a postback?

There a two different navigation menues on a page in their own seperate usercontrols. The menu items in the two menus can navigate to the same pages.
The topmenu has some jQuery animation and the leftmenu has not.
The question is how can I get which anchor tag in a navigation menu made a postback when the anchor tag is in a repeater and the repeater is in a usercontrol(The anchor tags are dynamically created). The problem is that the topmenu usercontrol codebehind runs and sets some values for hiddenfields so the jQuery animation will run properly for the topmenu, but when the leftmenu is clicked it should not run and set the hiddenfields in the topmenu codebehind. So I need to figure out how to differentiate between the two menus.
Here is the repeater markup:
<asp:Repeater runat="server" ID="RightSide">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li data-type="<%# ((Item)Container.DataItem).HasChildren ? "dropdown" : "link" %>" class="<%# ((Item)Container.DataItem).HasChildren ? "dropdown" : "link" %>">
<a href='<%# GetLink(((Item)Container.DataItem),"MenuLink") %>'><%#((Item)Container.DataItem)["MenuTitle"] %></a>
</li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
TopMenu .cs code:
public partial class TopMenu
{
private ID _homeId = new ID("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}");
protected void Page_Load(object sender, EventArgs e)
{
RightSide.DataSource = GetMultiList("Right side", RootItem);
RightSide.DataBind();
***HERE I NEED TO MAKE THE CHECK.
So the code below should only run if the postback came from the topmenu***
var sectionItem = GetAncestorOrDefault(CurrentItem);
Sitecore.Data.Database context = Sitecore.Context.Database;
Sitecore.Data.Items.Item homeItem = context.GetItem("/sitecore/content/home");
List<Item> items = new List<Item>();
Sitecore.Data.Fields.MultilistField multilistField = homeItem.Fields["Right Side"];
foreach (string id in multilistField)
{
Sitecore.Data.Items.Item multiItem = Sitecore.Context.Database.Items.GetItem(id);
if (multiItem.HasChildren)
{
items.Add(multiItem);
}
}
foreach (Item item in items)
{
if (item.Name.Equals(sectionItem.Name))
{
hiddenAttr.Value = sectionItem.Name;
break;
}
else
{
hiddenAttr.Value = String.Empty;
}
}
}
}
I have tried with eventtarget but it is always null and also with hidden field which value is always "" in the codebehind. I am out of ideas...
I will post more code if needed.
Thanks in advance!
Örvar
You are overwriting all values in postback. Wrap the code in if(!IsPostBack){} for repeater data binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RightSide.DataSource = GetMultiList("Right side", RootItem);
RightSide.DataBind();
}
else
{
// ***HERE I NEED TO MAKE THE CHECK.
// So the code below should only run if the postback came from the topmenu***
var sectionItem = GetAncestorOrDefault(CurrentItem);
Sitecore.Data.Database context = Sitecore.Context.Database;
Sitecore.Data.Items.Item homeItem = context.GetItem("/sitecore/content/home");
List<Item> items = new List<Item>();
Sitecore.Data.Fields.MultilistField multilistField = homeItem.Fields["Right Side"];
foreach (string id in multilistField)
{
Sitecore.Data.Items.Item multiItem = Sitecore.Context.Database.Items.GetItem(id);
if (multiItem.HasChildren)
{
items.Add(multiItem);
}
}
foreach (Item item in items)
{
if (item.Name.Equals(sectionItem.Name))
{
hiddenAttr.Value = sectionItem.Name;
break;
}
else
{
hiddenAttr.Value = String.Empty;
}
}
}
}
Also I would suggest using a query parameter in tag. If the href is
"/MyContent/MyPgae1"
you can change it to
"/MyContent/MyPgae1?s=r"
and in the postback :
if (!IsPostBack)
{
RightSide.DataSource = GetMultiList("Right side", RootItem);
RightSide.DataBind();
}
else
{
if(Request.QueryString["s"] == "r")
{
//request is from rightmenu
}

Asp.net passing values to the User control then display them

I'm trying to make a generic Search UserControl that can be given some values, based on those values the search results will display. However I'm currently trying to display the results of my values, and they always show up as my default values.
my UserControl code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ProductSearch.ascx.cs" Inherits="..." %>
<asp:Label ID="lblSearchWord" runat="server" />
<asp:Label ID="lblSearch" runat="server" />
Code Behind:
private string _searchWord = string.Empty;
private int _search = -1;
public string SearchWord
{
get { return _searchWord; }
set { _searchWord = value; }
}
public int Search
{
get { return _search; }
set { _search = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
lblGroupId.Text = LevelId.ToString();
lblSearchWord.Text = SearchWord;
}
When I press the search button on the main aspx.cs page I do the following:
protected void btnSearch_Click(object sender, EventArgs e)
{
ucPS.SearchWord = txtProductSearch.Text;
ucPS.Search = 1
}
My aspx page contains the following
<%# Register src="UserControls/ProductSearch.ascx" tagname="ProductSearch" tagprefix="ps" %>
<ps:ProductSearch id="ucPS" runat="server" />
My problem is that I can't use Query strings as the user might have selected some other things on this page that I need to keep the state of, however I did test that one and foudn it working.
Where am I going wrong? or is there an better alternative (except for query strings).
All variables in a page are disposed at the end of the page-lifecycle. Hence SearchWord will always be initialized with the default value on every postback.
You need to persist it somewehere else, for example in a ViewState variable.
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
return "";
else
return (String)ViewState["SearchWord"];
}
set { ViewState["SearchWord"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
ViewState["SearchWord"] = string.Empty;
return ViewState["SearchWord"];
}
set
{
ViewState["SearchWord"] = value;
}
}
and I use databind not pageload, this way your usercontrol doesn't load unless you call it.
protected override DataBind()
{
//you can add a condition here if you like
if(SearchWord != string.Empty)
lblSearchWord.Text = SearchWord;
}
to call this from aspx:
usercontrol.SearchWord = "my word";
usercontrol.DataBind();
and thats it..

Categories