I'm adding data to my listbox using this code :
SqlCommand cmd1 = new SqlCommand("SELECT U_Naam, U_Voornaam, User_ID FROM Login ORDER BY U_Naam ASC", con);
dr = cmd1.ExecuteReader();
int teller = 0;
while (dr.Read())
{
hulp = dr["U_Naam"].ToString() + " " + dr["U_Voornaam"].ToString();
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
teller++;
}
When I run the program and select an item in the list I want to get it's value (Using selectedvalue). When I do this it allways gives a nullref (no value). I've read somewhere the selected item is lost after a postback ? How can I solve this ?
thanks !
replace these lines
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
with
lbNiet.Items.Add(new ListItem(hulp,dr["User_ID"].ToString();));
I don't think the selected item is lost after PostBack under normal circumstances - my guess is that you are accidently populating the ListBox again after PostBack so that when you make a selection, the system hits the Page_Init / Page_Load (or whatever event you choose to populate the ListBox in) and recreates all the options. Doing this would overwrite the currently selected option.
If that's the case it's easily avoided by check for PostBack first before repopulating the list.
Are you running that code in the Load of your ASP.NET page without checking to see if it is a Postback? You should make sure to wrap your loading code in a if (!IsPostback) {} block if you're doing it in the load of the page.
Databinding your data instead of adding in a loop will help.
Are you using the ViewState for your page?
If yes, check the IsPostBack property of the page, and don't populate your list after postback.
you can use Request.Form to find the posted value
or I think if you use a scriptmanager and an updatepanel it refills the box after a postback
Related
I have the following project :
It's a page that on Page_Load it fills a TextBox named Email and a TextBox named UserName with a value obtained from asking a database.
Then there is this button, if the email is not null(user is not registered) it will let you register, otherwise it will let you change the email linked to your username.
The thing is, when trying to modify the email, doing an update query, the page preloads, taking the new value placed on Textbox Email the same that is retrieved from the database, making so it will never change.
I've tried to see if it executes the query and it does.
I've tried everything, keeping the variable on a hidden label, creating two different buttons with no luck as when it reloads the code those values are empty again.
I was thinking if I could keep the variable somehow that isn't cookies.
I think You know What is happening.. On every Post back the Page_Load event resetting your Textbox Value
Use IsPostBack to bind the value only on 1st load of page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind dropdown and fill textbox here
TxtName.Text = "Your values";
GetDropdowns();
}
}
I hope this will solve your issue
I totally agree with Kanis XXX, you can use IsPostBack to fill the values only at the start page, and not on other postbacks. In my experience, there are some other advices for your problems:
Using Viewstate, Session state,... to keep your working variable. You can have more detail here: https://kimphuc.wordpress.com/2009/10/18/the-difference-between-viewstate-sessionstate-cookies-and-cache-in-asp-net/
Try to use UpdatePanel, this could be useful in some cases, let you refresh or update data just a part of your page, not the whole page. https://msdn.microsoft.com/en-gb/library/bb398864%28v=vs.100%29.aspx
Hi I got this problem when trying to make an "edit" page for a profile stored in the database.
To make it simple, I got a textbox where i get a value from the database and apply it to the textbox with textbooks. text = "value";`.
Works great this far.
Then I want the user to be able to edit the text in the textbox and then press save, which should save the edited content of the textbox. But it doesn't, it saves the value i applied with textbox.text.
I get the value from the textbox in the button click function with textbox.text.
What am i doing wrong? - does the input from the user not overwrite the .text value?
TextBoxNavn.Text = "Navn";
protected void ButtonSave_Click(object sender, EventArgs e)
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE Politikere SET Navn = #Navn WHERE ID = #ID";
command.Parameters.AddWithValue("#Navn", TextBoxNavn.Text);
}
}
Between the first line and the update statement, the user has edited the text in the textbox, but it still saves the value from the first line.
If i remove the first line and enter a value in the textbox it saves the entered value. That's why i suspect that the issue is the .text - but i don't know how else to do.enter code here
EDIT
Sorry if i am not clear. but all values are entered and works great. Too great for some.
there's just too much code to point out small snippets for this. But by narrowing down the issue, I have found out that if i don't insert the database value with TextBoxNavn.Text in the page_load, it updates the value in the database with the new value. But when inserting it, user edited value does not get saved, but the value i inserted from the database does
EDIT II
The steps:
i get the data from the database and insert it into TextBoxNavn with TextBoxNavn.Text
The user will go to the page and edit the textbox, writing a new name in the TextBoxNavn
The user press "save" button
The value from the TextBoxNavn is retrieved by TextBoxNavn.Text
The value saved to the database is the value from step 1, but i need it to be the value from step 2
I am assuming that you are using DataBind() inside your page load. If yes please change it to`
if(!Page.IsPostBack)
{
DataBind();
}
`
or else share the complete code where you bind the data to your textbox. If you bind your controls on PageLoad, Bind will be called before the control events and in that case the value you entered will be over ridden by the Databind() function. Pleae refer the following link for the asp.net page life cycle.
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
I have a RadioButtonList with 2 items. I want a postback when any of the items is selected. I have added a confirm box for one item of RadioButtonList. But, when I click OK in the confirmbox, there is no postback and SelectedIndexChanged event is not getting fired.
AutoPostback property of RadioButtonList is set to true.
This is a code fragment from my Page_Load method:
RadioButtonOpenRestricted.Attributes.Add("AutoPostBack", "True");
RadioButtonOpenRestricted.Items.FindByValue("Open Access").Attributes.Add("AutoPostBack", "True");
RadioButtonOpenRestricted.Items.FindByValue("Open Access").Attributes.Add("OnClick", "javascript:return confirm('Are you sure?');");
Earlier, I had added confirm box for entire RadioButtonList and postback was working as expected. But I want the confirm box to be displayed only when user clicks on "Open Access" item.
Please help!
I tried a few things. The new code lines look like:
RadioButtonOpenRestricted.Items.FindByValue("Open Access").Attributes.Add("OnClick", "javascript:showConfirmBox(0,'" + RadioButtonOpenRestricted.ClientID + "')");
RadioButtonOpenRestricted.Items.FindByValue("Restricted Access").Attributes.Add("OnClick", "javascript:showConfirmBox(1,'" + RadioButtonOpenRestricted.ClientID + "')");
The javascript method is:
function showConfirmBox(i,id)
{
if(i==0)
{
if (confirm("Are you sure you want to provide Open Access? All existing individual permissions will be removed!")==true)
{
var ctrl1 = document.getElementById(id + "_0");
ctrl1.selected=true;
}
else
{
var ctrl2 = document.getElementById(id + "_1");
ctrl2.selected=true;
}
}
if(i==1)
{
var ctrl2 = document.getElementById(id + "_1");
ctrl2.selected=true;
}
}
The problem with this code is that it is treating both OK and Cancel as same. The confirm box is getting displayed but if-else part of the javascript method is not getting called. I tried using OnClientClick also...this doesnt even display the Confirmbox.
Help!!!
This is because your on click script does not play well with auto-post back script generated by the ASP.NET. A quick hack solution can be
RadioButtonOpenRestricted.AutoPostBack = true;
RadioButtonOpenRestricted.Items.FindByValue("Open Access").Attributes.Add("OnClick", "if (!confirm('Are you sure?')) return false;");
Although, this will still give you an issue when you cancel on your confirmation box (in such case, you have to add script to select the previous radio button again).
As such I am not a great fan of radio button list - you may consider alternate mechanism such as repeater with radio button in item template and having your own java-script for confirmation.
I think you want to use OnClientClick to show a "confirm" window.
I don't think you can have a javascript confirm window perform a postback, at least not the way your code is set up.
You should set the OnClientClick to show a confirm modal or window with an <asp:Button/> and have that button perform the postback your looking for.
Khushboo, it used to happen with me many times. The reason behind that was I was missing some closing tag somewhere in my aspx page. I used to copy my whole aspx page to some other text editor and paste all the elements one by one to my aspx page. It always solved my this problem. I am sure you must be missing some closing tag, please cross check all elements.
I've got the following DropDownList control:
<asp:DropDownList ID="SubjectFilter" runat="server" AutoPostBack="True" onselectedindexchanged="SubjectFilter_SelectedIndexChanged"></asp:DropDownList>
SubjectFilter data:
BookStore b = new BookStore();
b.LoadFromXML(Server.MapPath("list.xml"));
SubjectFilter.DataSource = b.BooksList.Select(x => x.Subject).Distinct().ToArray();
SubjectFilter.DataBind();
SubjectFilter.Items.Insert(0, new ListItem("הכל", "Default"));
Everything loads just fine. However in the SubjectFilter_SelectedIndexChanged method, SubjectFilter.SelectedValue is always Default, even though I'm selecting different options.
What is the problem?
Thank you very much.
I'm guessing the above code is from the PageLoad event. You may want to wrap that in a if(!isPostBack) block.
Make sure that in your Page_Load that you only populate the dropdown when IsPostBack is false.
For example
public void Page_Load(...)
{
if (!IsPostback())
UpdateDisplay();
}
When are you binding the drop down? You may any to wrap in an
If(page.ispostback ==false)
It looks like you may be binding on page load, before you check its value..
ViewState is assigned between the Init and Load for an ASP.NET page. Your event handlers occur after load. If you are programmatically setting content in the controls that your user will be using, you want to handle that before ViewState is applied. In other words, move it to Page_Init. Afterwards, ViewState kicks in and you'll see what the user actually selected when your handler executes.
How do I get the id's of all the checkboxes generated by a checkboxlist, with datatable as its data source?
I think I have to use the "OnDataBinding" event of the checkbox list, but I don't see how that will help me.
I am using C#
I don't think getting the id's of all the check boxes generated by the check box list is possible, so I think going the moo tools way is the right thing to do.
Any ideas?
Thanks
Ideally you would want to just attach the click event handlers to all your checkbox lists in the domReady event and this will create a much simpler function with MooTools. However, you can keep your code as-is if you prefer and just make your 2 functions a little simpler.
function ToggleSelection(ctrl, sender) {
var checkboxes = $(ctrl).getElements('input[type=checkbox]');
checkboxes.set('checked', sender.checked);
}
function ToggleSelectAll(ctrl, sender) {
var fAllChecked = ($(sender).getElements('input:checked').length == $(sender).getElements('input[type=checkbox]').length)
$(ctrl).set('checked', fAllChecked);
}
You can set the properties of your entire ELements array at once, you don't need to loop through them. In the 2nd function, I'm checking the number of elements that are checked against the total number of checkboxes and if they match that means they are all checked.
Are you using VB or C#..please tag accordingly
You can have List or string called strchklist
VB.NET
For Each li In CheckBoxList1.Items
If li.Selected Then
strchklist += li.Id
End If
Next
C#
foreach (ListItem li in CheckBoxList1.Items){
If li.Selected
strchklist += li.Id ;}
The <asp:ListItem> is not really a Control itself therefore has no ID. If you want to access it in client script add a new attribute you can reference. (yes, during OnDataBinding) Remember that these are not persisted in the ViewState however!
What exactly are you trying to accomplish? May help to elaborate somewhat.
Completely different answer...
The CheckBoxList is a bit of an odd duck... unlike other controls, it does not really have a logical mapping to an obvious HTML construct. It actually renders multiple checkboxes with derivative IDs. Those IDs seem to be generated as CheckBoxList.ClientID + "_" + ItemIndex.
You can verify this by looking at the page source. Internally, it seems the ID of the individual checkbox control is just its index, and then it's rendered with the CheckBoxList as its NamingContainer. You can use Reflector is see how the CheckBoxList control renders the output.
Still a good spot for jQuery. Just easier now you know the IDs.
I woke up this morning and thought of doing this (cblUSEquities is a checkbox list)
cblUSEquities.Attributes.Add("onclick", "javascript:alert('Clicked');");
This adds the alert to the table that the checkbox list generates. One thing to note is, the alert shows up twice If I click the text of the checkbox and once if I click the checkbox. I think this solution will work for me.
BTW, I never thought that the above code would work...
P.S Answering my own question because I wanted to write some code, which I cannot do using the comment box.
In the spirit of StackOverFlow, I arrived to something which works in my scenario but the description of the question is different? What do I do? Edit the question and mark this as answer?
I was able to do this by using mootools and this is the code.
function ToggleSelection(ctrl, sender)
{
var cblCtrl = $(ctrl);
var Allcbs = cblCtrl.getElements('input');
for(var i=0; i<Allcbs.length; i++)
Allcbs[i].checked = sender.checked;
}
function ToggleSelectAll(ctrl, sender)
{
var AllTrueCount = 0;
var cblCtrl = $(ctrl);
var Allcbs = sender.getElements('input');
for(var i=0; i<Allcbs.length; i++)
if(Allcbs[i].checked)
AllTrueCount++;
if(AllTrueCount == Allcbs.length)
cblCtrl.checked = true;
else
cblCtrl.checked = false;
}
C# code which calls the javascript functions
//Binding event to the checkbox list
cblUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelectAll('{0}', this);", chkAllUSEquities.ClientID));
//binding event to the select all checkbox
chkAllUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelection('{0}', this);", cblUSEquities.ClientID));
As it turns out I did not need to know the id's of all the checkboxes generated by the checkbox list. I was able to add the onclick javascript to those checkboxes by this line
cblUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelectAll('{0}', this);", chkAllUSEquities.ClientID));
Which will add the onclick event to the table that the checkbox list generates.