How to store the state of my check box list tick boxes accross the page life cycle?
Here i have a unbound checkbox list control where values comes from xml file.
how to retain the state?
Moreover, when i click on Next button to the new page and comeback state is retained.
But when i click on the back button and come to the same page state is not retained
Protected Sub chkBx_SR_wu_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles chkBx_SR_wu.SelectedIndexChanged
Dim i As Integer
i = 0
Try
For i = 0 To chkBx_SR_wu.Items.Count - 1
If chkBx_SR_wu.Items(i).Selected Then
Select Case chkBx_SR_wu.Items(i).Value
Case "SR_MR"
chkbx_SR.Checked = True
Case "Sk_MR"
chkbx_SkRoom.Checked = True
Case "SC_SS"
chkbx_admin.Checked = True
Case "CS_MR"
chkbx_salesFloor.Checked = True
Case "TEAM_LEADER"
rb_tl.Enabled = True
chkbx_tlAdmin.Enabled = True
chkbx_tlJewellery.Enabled = True
chkbx_tlSalesFloor.Enabled = True
chkbx_tlSkRoom.Enabled = True
rb_tl.Items(0).Enabled = True
rb_tl.Items(1).Enabled = True
rb_tl.Items(2).Enabled = True
rb_tl.Items(3).Enabled = True
ReqiredFieldValidator1.Enabled = True
End Select
Else
Select Case chkBx_SR_wu.Items(i).Value
Case "SR_MR"
chkbx_SR.Enabled = False
chkbx_SR.Checked = False
Case "Sk_MR"
chkbx_SkRoom.Enabled = False
chkbx_SkRoom.Checked = False
Case "SC_SS"
chkbx_admin.Enabled = False
chkbx_admin.Checked = False
Case "CS_MR"
chkbx_salesFloor.Enabled = False
chkbx_salesFloor.Checked = False
Case "TEAM_LEADER"
chkbx_tlAdmin.Enabled = False
chkbx_tlAdmin.Checked = False
chkbx_tlJewellery.Enabled = False
chkbx_tlJewellery.Checked = False
chkbx_tlSalesFloor.Enabled = False
chkbx_tlSalesFloor.Checked = False
chkbx_tlSkRoom.Enabled = False
chkbx_tlSkRoom.Checked = False
rb_tl.Items(0).Enabled = False
rb_tl.Items(1).Enabled = False
rb_tl.Items(2).Enabled = False
rb_tl.Items(3).Enabled = False
ReqiredFieldValidator1.Enabled = False
End Select
End If
Next
Catch ex As Exception
End Try
End Sub"
My first guess, without seeing your code, is that you're binding the checkboxlist on Page_Load without checking to see if the page load is a postback. Do that and it should fix the problem.
You need to check where you are binding data to the checklist box. The problem isn't in the code you posted but where ever you are binding the code. Make sure you are checking for IsPostBack to be false or else every time your page loads, you will be rebinding your data and losing all your state. You should only bind once. Eg (in C#):
if (!IsPostBack)
{
BindMyDataToCheckBoxList();
}
Put a break point on where you binding the data, I bet everytime you doing anything like click a button or whatever, that binding code is getting hit which it probably shouldn't be.
There's no guaranteed method of having the values retained if they visit the page again but not if they use the back button. You could try setting the page headers so that the page is not cached as a precaution against the user seeing invalid data.
In the Page_Init stage of the page lifecycle, you can populate your checkbox list with the values from your XML file, and then in the Page_Load stage, check that the page isn't be posted back and select the checkboxes accordingly using the values in the session.
Eg. in C# -
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Populate checkbox list from XML
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> list = Session["MyList"] as List<string>;
if (list != null)
{
foreach (int val in list)
{
ListItem chk = myCheckBoxList.Item.FindByValue(val);
if (chk != null)
chk.Checked = true;
}
}
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
List<string> list = new List<string>();
foreach (ListItem li in myCheckBoxList.Items)
{
if (li.Checked)
{
list.Add(li.Value);
}
}
Session["MyList"] = list;
}
This code hasn't been tested, but could be used a starting point. You can convert the code to VB.NET using a code converter, such as the one from Telerik.
You can retain state of checkboxes across/on pages either by:
Cookie
Sessions
ViewState
or Save it in
Database.
I would recommend Sessions as it is quite trivial to use, and does not require them to have cookies enabled.
A simple tutorial on sessions can be found here. That is a c# version.
Here is a vb.net example (but not from MSDN)
Related
I have a form with many drop down list boxes on. Each of which I am showing or hiding a row of a table based on its value then adding a requiredfieldvalidator to the text box contained in that row. I am doing this on the selectedindexchanged event of each drop down list, the code for which can be seen below:
Protected Sub cbOffCover_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbOffCover.SelectedIndexChanged
If cbOffCover.SelectedValue = "N" Then
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
End Sub
I then reuse this code for each drop down list to show/hide a differently named row and apply validation to a different text box.
My question being is there a better way of doing this? I don't know exactly how but I can't help but think I don't have to write this much code (or copy/paste) over and over again for each drop down list. Is it possible to write a function/class that will do the work and I can just call that instead? Might seem basic but i'm new to asp/vb. Many thanks
You can put it in a function that returns a boolean. When you call the function, pass it the combobox itself and whatever values you want to validate against. If it matches, return true. Try something like this:
Public Function ValidateComboBox(someComboBox as ComboBox, expectedValue as String)
Dim result as Boolean = False
If someComboBox.SelectedValue = expectedValue Then
result = True
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
Return result
End Function
Of course, modify it to fit your needs. Maybe you only return the value, and do the other stuff inside the control's SelectedIndexChanged method.
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.
I have an initialize function that loads data into my textbox NameTextBox, and then I add an "s" to the name. I then click the Save button that executes SaveButton_Click when debugging the value for NameTextBox.Text is still the original string (FirstName) and not (FirstNames). Why is this? Thanks.
Edit: Sorry here you go let me know if you need more...
Page_Load(sender, e)
Info = GetMyInfo()
Initialize()
Initialize()
NameTextBox.Text = Info.Name
SaveButton_Click(sender, e)
Dim command As SqlCommand
command = GetSQLCommand("StoredProcedure")
command.Parameters.AddWithValue("#Paramter", NameTextBox.Text)
ExecuteSQLCommand(command)
If the textbox is disabled it will not be persisted back to the codebehind, also if you set the initial value everytime (regardless of IsPostBack) you are essentially over writing what the value is when it gets to the Event handler (SaveButton_Click). Ex:
page_load() { NameTextBox.Text = "someValue";}
....
saveButton_Click() { string x = NameTextBox.Text;}
The above code will always have the text value of the textbox be "someValue". You would need to wrap it in an if(!IsPostBack) like so....
page_load() { if(!IsPostBack) {NameTextBox.Text = "someValue";}}
....
saveButton_Click() { string x = NameTextBox.Text;}
I have to disable all the controls on my gridview for business purposes.
Me.gvLineItems.Enabled=False
However, I need to enable one hyperlink field enabled so I tried this:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim hrf As HyperLink
hrf = CType(Row.Cells(16).Controls(0), HyperLink)
hrf.Enabled = True
Next
I debug the code and it sets the hyperlink field enabled to true, but when I run the app the field is still disabled...
But If I get rid of the Me.gvLineItems.Enabled=False just comment that out and change my code to DISABLE the hyperlink field:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim hrf As HyperLink
hrf = CType(Row.Cells(16).Controls(0), HyperLink)
hrf.Enabled = False
Next
This works fine...
But that is not what I need :(, just trying to reenable the link field...
Edit
I also tried this in the rowdatabound event:
If Me.gvLineItems.Enabled = False Then
For i As Integer = 0 To e.Row.Cells.Count - 1
If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
h.Enabled = True
Exit For
End If
Next
End If
I got it with this:
For i As Integer = 0 To e.Row.Cells.Count - 1
If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
h.Enabled = True
Exit For
Else
e.Row.Cells(i).Enabled = False
End If
Next
You'll need to use some type of recursive logic to loop through all the cells and disable the controls, with a condition to exclude HyperLink controls. By disabling the controls at the row level, the enabled state of the parent container (i.e. GridViewRow) will always override the enabled state of the control.
I would add some recursive logic in the RowDataBound event. Try something like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DisableControls(e.Row);
}
private void DisableControls(WebControl parentCtrl)
{
if (parentCtrl.HasControls())
{
foreach (WebControl ctrl in parentCtrl.Controls)
{
ctrl.Enabled = ctrl is HyperLink;
DisableControls(ctrl);
}
}
else
{
parentCtrl.Enabled = parentCtrl is HyperLink;
}
}
I know the question is a little choppy and perhaps misleading,but I have a gridview with dropdownlists on the rows. I created an AddHandler and a Delegate for the SelectedIndexChanged and it gets to the sub. Here is the code for that:
AddHandler ddlmgr.SelectedIndexChanged, AddressOf ddlmgr_SelectedIndexChanged
Public Delegate Sub DropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As DropDownList_SelectedIndexChanged)
Protected Sub ddlmgr_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
End Sub
How can i get the row's Id if GridView_RowCommand is not called?
You will need to do a bit of the legwork as I cant provide 100% specifics without writing out the code and testing it on my own here, which I am unable to do at present, but the code should go along these lines.
within the ddlmgr_SelectedIndexChaged,
cast your sender to a DropDownList
access the part property of the dropdownlist.
Check it is is a GridItem (or repeateritem or whichever, you get the idea)
If so, get the items itemindex. If not access its parent property.
Continue until you find your Row object.
Hopefully this helps. If not, perhaps someone with a bit more liberal access can chime in
DropDownList ddl = (DropDownList)sender;
Control p = ddl.Parent;
//you are going to loop because the immediate
//parent may not be the repeater item but instead a
//container control of some kind (say a template)
while (p.GetType() != typeof(RepeaterItem))
{
p = p.Parent;
if (p == null) return; //we have reached the top of the control tree
}
RepeaterItem ri = (RepeaterItem)p;
int index = ri.ItemIndex
return index;
Great work
Works absolutely fine for me
DropDownList ddl = (DropDownList)sender;
Control p = ddl.Parent;
//you are going to loop because the immediate
//parent may not be the repeater item but instead a
//container control of some kind (say a template)
while (p.GetType() != typeof(RepeaterItem))
{
p = p.Parent;
if (p == null)
return; //we have reached the top of the control tree
}
RepeaterItem ri = (RepeaterItem)p;
int index = ri.ItemIndexreturn index;
DropDownList ddltxt = (DropDownList)sender;
string temp2 = ddltxt.SelectedItem.Text;
string temp3 = ddltxt.SelectedItem.Value;
string temp = ddltxt.ID.ToString();
int strlength = temp.Length;
string strLastchar = temp.Substring(strlength - 1, 1);
int intlastchar = int.Parse(strLastchar.ToString());
string commonpart = temp.Substring(0, strlength - 1);
if (intlastchar == 1)
{
string targetdropdownid = commonpart + "2";
DropDownList targetlist = (DropDownList)TableRow11.FindControl(targetdropdownid);
using (conn = new SqlConnection(ConnectionString))