Is ctl00 a constant in ASP NET? - asp.net

I need to reference a control in my web app that was generated with the use of a master page. The name of the control in the HTML becomes something like this "ctl00$MainContent$ListBox1". Can I safely do this in the code?
string strName = "ctl00$MainContent$ListBox1";
if (Request.Form[strName] != null)
{
String selectedLanguage = Request.Form[strName];
}
PS. I cannot use ClientID property because this code is called from InitializeCulture() override.

You could, but what I do is set the MasterPage ID in my Init():
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}

ctl00 is the generated ID of your masterpage. In the code-behind, you can set this.ID to whatever you want and any sub-content will be prefixed with that ID instead.
The problem with the code you have above is you're relying on a magic string for a control ID - you need to be careful with this as controls get moved into user controls and master pages become nested. I'm not sure why you can't use ListBox1.SelectedValue?

Related

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

Retain textbox values on page refresh

I have a textbox in a user control uc1. I have embedded this uc1 in a page called default.aspx. My issue is after running the application and entering some data in the textbox, when refresh the page i would like to show the values that i have entered in the textbox and not clear the textbox. I would like help with code on how to achive this. Thanks in advance for your help.
Create a global variable at the top of your aspx.cs page:
public string textboxValue
{
get
{
if (ViewState["textboxValue"] != null)
return ViewState["textboxValue"].toString();
else
return "";
}
set
{
ViewState["textboxValue"] = value;
}
}
Then, in PageLoad(), assign textboxValue a value:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
textboxValue = MyTextBox.Value;
else
MyTextBox.Value = textboxValue;
}
You can also use textboxValue to assign the value of MyTextBox at any time, or use it in any other way that might be useful to you.
The default behavior for all asp.net server side controls (runat="server") is to maintain their state. If your textbox is being cleared when your page refreshes, you are likely clearing that value yourself in code.
Are you dynamically adding the textbox or user control? If so, are you doing that during PageInit? Adding them later may cause them to lose state.
I was able to refresh the page without clearing the value in textbox. I did it as below:
I created a public property in the UC1.vb as below:
Public Property textbox_value() As String
Get
If Session("textbox1") IsNot Nothing Then
Return Session("textbox1").ToString()
Else
Return ""
End If
End Get
Set(value As String)
Session("textbox1") = value
End Set
End Property
And in the page_load event of the user control i added the code below:
If IsPostBack Then
textbox_value= textbox1.Text
ElseIf Not IsPostBack Then ' First time the page is loaded or when the page is refreshed
textbox1.Text = textbox_value
End If
Hope it helps.

ASP.NET Is it possible to handle all the null session checking in masterpage

I have the following steps in my webpage
1) User Logs in and I set the following session variables
Session("userName") = reader_login("useremail").ToString()
Session("userId") = reader_login("user_ID").ToString()
Session("firstName") = reader_login("firstName").ToString()
2) Now on my logged in VB.NET templates I reference a MasterPage called LoggedIn.Master. In Which I added the following method to check for the above null session variables. And if they null to redirect back to login page.
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
'#Check that User is Logged in, if not redirect to login page
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
3) Now my question is if I want to use any above 3 Session variables in different .net templates or usercontrols referencing the above master page do i need to AGAIN add the check
If (Session("userId") Is Nothing) Or (Session("userName") Is Nothing) Or (Session("firstName") Is Nothing) Then
Response.Redirect(ConfigurationManager.AppSettings("site_base_url").ToString & "login/", False)
End If
In the respective pages or will the check in master page do. Because at the moment i.e. if in a usercontrol I attempt to do i.e.
customerName.Text = Session("userName").ToString()
or
Response.Write(Session("userName").ToString())
I am getting the error
Object reference not set to an instance of an object.
customerName.Text = Session("userName").ToString()
You can write a wrapper around the Session to handle null values and just call the wrapper when you access the items:
Public Class SessionWrapper
Public Shared ReadOnly Property Item()
'Access session here and check for nothing
End Property
End Class
And use it like this
SessionWrapper.Item("itemName")
In answer to your question - as long as the masterpage checks the session and redirects before all your controls and page code make a reference to Session, you should be fine.
You were using OnInit() which seems reasonable, but see this article for a good understanding of the timing of events.
Incidentally, I strongly discourage the use of ad-hoc calls to Session in your page and control code. Instead, I recommend you create a static SessionManager class that does the Session referencing for you. That way, you get to benefit from strong typing, and won't be able to accidentally make hard-to-debug 'session key' typos in your code like Session["FiirstName"]. Also, you can incorporate your null-session check right into the call for the session value:
EXAMPLE (in C#, sorry!)
public static class SessionManager
{
private static void EnsureUserId()
{
if (Session["userId"] == null)
{
Response.Redirect("YourLogin.aspx", false);
}
}
public static string FirstName
{
get
{
EnsureUserId();
if (Session["firstName"] == null)
Session["firstName"] = "";
return (string)Session["firstName"];
}
set
{
Session["firstName"] = value;
}
}
}
You can create an http module that asks about the session objects and if they are null, it will redirect to the login page and by developing this http module, in each page request the module will do the check and then you can use it normally without checking.
A better way to handle this would be to add a base class for all controls that require this session variables to be present. You can then add properties to wrap access to the session and other cool stuff and the check will work even if the controls are used with a different master page.

How to pass variable from page to another page in ASP.NET

I want to ask how to pass a variable from a page to another page.
example.
in (page1.aspx.cs) there is button click and textbox
protected void Button1_Click(object sender, EventArgs e)
{
textbox1.text = ;
}
in (page2.aspx.cs)
A = "hello"
// A is variable that can be change, A variable is coming from microC
What I want is show "hello" from page2 in textbox1.text when I click button1 in page1.aspx
You can pass the value as a querystring parameter.
So if you are using Response.Redirect you could do something like
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Page2.aspx?value=" + taxtbox1.text);
}
On Page 2 you can get the value using Request["value"].ToString()
Notice that the querystring parameter name is what you request. So if you have ?something=else you will Request["something"]
One way is to place the value into some form of temporary storage: Cookie, Session, etc. And then redirect.
Another would be to redirect with a query string value. It really depends on your situation.
I'd recommend setting a session if this is necessary.
Session["sessionname"] = "";
Though it isn't ideal, is it possible to have everything on page1? You can switch with a panel control.
Without a Postback it is not possible!
With a Postback, yes it is (see Cross Page Postback). Also see in the link what you can have access to! (Access possibilities are page controls & public members).
Other options, Session variables, cookies, query string, etc!
u can use one of this ways:
1- Query string
page.aspx?ID=111&&Name=ahmed
2- Session
Session["session1"] = "your value";
3- Public property
public String prop1
{
get
{
return txt_Name.Text;
}
}
4- Controls Data
5- HttpPost

How can I use a page_load local variable in event handler of a button

Im making a site in Visual Studio using vb and I have a variable in page_load but need its value in the event handler of a button for passing on session.
Any suggestions on how I can do this? Any help is appreciated
You can store a value in the CommandArgument property of a Button:
btn.CommandArgument = "Your value"
And then when handling the event you can pull it out:
CType(sender, Button).CommandArgument
You could also make a new class that extends Button and create new properties like below if you need multiple arguments:
Class SessionButton
Inherits Button
Public Property SessionGUID() As Guid
Get
Dim s As Guid = Nothing
If Not String.IsNullOrEmpty(ViewState("SessionGUID")) Then
s = New Guid(ViewState("SessionGUID").ToString())
End If
Return s
End Get
Set(ByVal value As Guid)
ViewState("SessionGUID") = value.ToString()
End Set
End Property
End Class
couldn't you just make the variable a class scoped variable, instead of local?
You can store it in a viewstate backed property:
Public Property MyStringVar() As String
Get
If ViewState("MyStringVar") = Nothing Then
Return String.Empty
End If
Return ViewState("MyStringVar").ToString()
End Get
Set
ViewState("MyStringVar") = value
End Set
End Property
Now using this property you can save your variable on page load and access it in the button click event handler.
EDIT: updated to VB
you declare the variable outside the page_load and then you can use it where you want :)
You could also create a class that encapsulates the action. Then you can capture any data you want and easily add to it later.
void Page_Load()
{
myBtn.Click += new MyButtonClass(variable).Run;
}
class MyButtonClass
{
int Param;
MyButtonClass(int param)
{
Param = param;
}
public void Run(object sender, EventArgs args)
{
// Do something usefull
}
}
If the data is created/retrieved on every Page_Load, this will work. If it is wrapped around an (! IsPostBack), the data must be stored in a session. Fortunatly, the class can be easily modified to store/load the variable from a session parameter.
I'm sorry for the c# code, maybe someone else can translate it then remove this message?

Resources