I've looked around and tried to find a solution but haven't been able to find one I could adapt to my issue.
Basically I got a repeater pulling paths to images out of a SQL database, with it there are 3 value defining height, width, and price, this is shown with 3 labels under the image. However I don't want the label to show if the values are 0, so I wrote this foreach to sort it:
foreach (RepeaterItem Rep1 in Repeater1.Items)
{
//assigns a temporary variable the value of the control we find.
Label nullPris = (Label)Rep1.FindControl("PrisLabel");
Label nullHeight = (Label)Rep1.FindControl("HeightLabel");
Label nullWidth = (Label)Rep1.FindControl("WidthLabel");
//Checks if the lable has the text we're looking for.
if (nullPris.Text == "0,00 Kr.-" || nullPris.Text == "0.00 Kr.-")
{
//If it has, stop rendering the label.
nullPris.Visible = false;
}
if (nullHeight.Text == "Højde: 0,00 cm" || nullHeight.Text == "Højde: 0.00 cm")
{
//If it has, stop rendering the label.
nullHeight.Visible = false;
}
//Checks if the lable has the text we're looking for.
if (nullWidth.Text == " Bredde: 0,00 cm" || nullWidth.Text == "Bredde: 0.00 cm")
{
//If it has, toggle the visibility..
nullWidth.Visible = false;
}
}
The code itself works as intended, however I've run into 2 issues:
If I call the code in any of the Page_Events it doesn't work, the code runs but doesn't find the repeater so skips the rest entirely, it dosen't matter if I put it in Page_Load or Page_Unload, both seems to be executed before the repeater has done its job.
Secondly I got around this by calling the code via OnLoad on the labels themselves, but then the last loaded item isn't affected, this happens regardless of the amount of items in the database.
Thanks in advance!
I found a solution to my problem that didn't require me to wait for the page to load.
I found other people with a similar problem using a For each loop on items created by a repeater, so I took out the loop and instead executed the code each time a new item was bound to the repeater using the OnItemDataBound method, so my revised code looks like this:
protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
{
//assigns a temporary variable the value of the control we find.
Label nullPris = (Label)e.Item.FindControl("PrisLabel");
Label nullHeight = (Label)e.Item.FindControl("HeightLabel");
Label nullWidth = (Label)e.Item.FindControl("WidthLabel");
//Checks if the lable has the text we're looking for.
if (nullPris.Text == "0,00 Kr.-" || nullPris.Text == "0.00 Kr.-")
{
//If it has, stop rendering the label.
nullPris.Visible = false;
}
if (nullHeight.Text == "Højde: 0,00 cm" || nullHeight.Text == "Højde: 0.00 cm")
{
//If it has, stop rendering the label.
nullHeight.Visible = false;
}
//Checks if the lable has the text we're looking for.
if (nullWidth.Text == " Bredde: 0,00 cm" || nullWidth.Text == "Bredde: 0.00 cm")
{
//If it has, toggle the visibility..
nullWidth.Visible = false;
}
}
}
if possible try looking at ajax calls/javascript basically you want to fire a function when the document is ready...right?
A small description of what I'm trying to say
Related
I am making myself a project manager and I need to refresh Project List every so often. When I am refreshing the Project Manager, I want to select the item that was previously selected. But that selection causes my text box to unselect, therefore, what happens is that that text box unselects after typing one key.
So outline what happens:
I try to edit one text box
Edition causes update in project -> program calls RefreshProjectList()
RefreshProjectList() on marked position causes selected text box to unselect
Result: You must select text box after writing one symbol
Picture if useful
These selected text boxes are struggling to be edited
Code:
private void RefreshProjectList() {
if (BlockListReload)
return;
Project selected = (Project)ProjectList.SelectedItem;
ProjectList.Items.Clear();
CurrentlyShown.Clear();
foreach(Project p in Projects){
if (p.state == State.Planned && ShowPlanned.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Active && ShowActive.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Finished && ShowFinished.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
if (p.state == State.Delayed && ShowDelayed.Checked) {
CurrentlyShown.Add(p);
ProjectList.Items.Add(p);
}
}
if (selected == null)
return;
if (ProjectList.Items.Contains(selected)) {
ProjectList.SelectedItem = selected; // IF I REMOVE THIS
} else {
if (ProjectList.Items.Count > 0)
ProjectList.SelectedIndex = 0; // OR THIS LINE, EVERYTHING WORKS
}
}
If you need more code, I will be happy to provide, but I don't want to spam you with loads of unuseful code.
Q: Why does changing selected item in ListBox cause deselecting of TextBox and how to prevent it?
Several controls that have selectable text or items also come with a property HideSelection.
This includes:
TextBox
RichTextBox
ListView
but not
ListBox
CheckedListBox
DataGridView
Like it or not it always defaults to true so the selection is hidden whenever the focus is off the control..
Simply set it to false in the designer and you can see all selection no matter where the focus is..
OMG. I honestly don't know why I did not see it.
ProjectList.SelectedItem = selected;
//where ProjectList is ListBox<Project> and selected is Project
I am selecting an item in the ProjectList(ListBox). I didn't realize that it was calling a ProjectList_SelectedIndexChanged() event which was doing it.
EDIT: SOLVED by adding this:
if (focused != null) {
this.ActiveControl = focused;
focused.Select(focused.TextLength,0);
}
Where focused is a TextBox I set to last selected TextBox and this is the form.
Thanks TaW.
What I want to do is creating a menu with several buttons and when the user clicks on one of them, the selected button tag gets stored in a variable and the background color of that button gets highlighted. When the user clicks another button, the previous stored variable gets compared with the new variable and if it is different, it changes the background color of the earlier pressed button back to normal. This is what I have so far:
if (!isSelected)
{
b.BackColor = Color.FromArgb(28, 145, 162);
previousPress = (int)b.Tag;
isSelected = true;
if(previousPress != currentPress)
{
b(previousPress).BackColor = Color.FromArgb(12, 34, 567); // Obviously this wont work, but hopefully it clears up on what I want to reach.
isSelected = false;
currentPress = (int)b.Tag;
}
}
The .Tag idea of B is ranging from 1 till 7, as that is how many buttons are created in the constructor method.
That is what I tried to use, but someone suggested I shouldn't be using tags for this, as it should only cause bugs and errors. He suggested the following:
Button previousButton = b;
if (previousButton != currentButton)
...
I understand the logic behind this, but sadly before he went away before I could ask where and how the currentButton variable is declared/used. Could someone shine some light upon this? Thank you!
Assuming that all the buttons are assigned the same Click event, this code would do exactly what you want:
Color _activeColor = Color.Red;
private void buttons_Click(object sender, EventArgs e)
{
foreach (Button btn in this.Controls.OfType<Button>()
.Where(b => b.BackColor == _activeColor))
{
btn.BackColor = SystemColors.Control;
}
((Button)sender).BackColor = _activeColor;
}
It clears out the button who previously had _activeColor and sets the color to the current one.
This is pretty common approach to what (I believe) you need. Try to understand this code before trying it, it's relying on Linq.
I have a ListView with MultiSelect = false, View = Details and CheckBoxes = True. I'm stepping through it and controlling visibility in an application. I'm currently just using the Else portion of the code below. But it doesn't account for the first Item being selected, it just turns the second item on. And whether or not the item is checked (already visible), and it turns the visibility off. I'm comparing elements associated with the items against elements that are already visible. My app crashes at the currentItem.Checked loop. And doesn't account for combinations (first and checked). How could I code this?
int indexCount = listView1.Items.Count;
ListViewItem currentItem = listView1.SelectedItems[0];
int currentIndex = currentItem.Index;
if (currentItem.Index == 0)
{
//listView1.SelectedItems[0] on
}
if (currentItem.Index == indexCount)
{
//end
}
if (currentItem.Checked == true)
{
while (currentItem.Checked == true)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(currentIndex + 1);
}
//listView1.SelectedItems[0] on
}
else
{
//listView1.SelectedItems[0] off
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(currentIndex + 1);
//listView1.SelectedItems[0] on
}
It is not clear what you are trying to do.
You are basically picking one selected item and placing it in 'currentItem'. If that item is checked as true you are looping through it until? and why?
I created a few radiobuttonlist controls on my project, they're created every time the page is loaded, i want to get the value of the radiobutton that the user has selected, but since my radiobuttons were created dynamically, i don't know how to acces to their values nor how to create their event handlers. Is there a way to assign a name or id to the control when i create it?
i hope you can help me.
I create a seires of radiobuttlist on the page_load event, with the text and their values been pulled out of a database. now, the user has to choose one of the options from that radiobuttlist and i want to get the value of the radiobutton the user checked. how do i do that if i don't know the name nor the id of the radiobuttlist since they're created dynamically.
this is what i've got:
for (int i = 3; i < numfields; i++) {
if (dr[i].ToString() != "" && dr[i] != null){
r.Items.Add(new ListItem(dr[i].ToString(), dr[i].ToString()));
//r.SelectedIndexChanged += new EventHandler(rowSelectedIndex);
}
}
so basically i use my datareader to loop through the data in the database, if the value from the field isn't empty or null, then i add an item to the radiobuttlist called "r"
i tried to create an eventhandler for that too, but since i have never worked with them i really don't know what to do. :(
I'm so sorry if i seem way too pathetic.
Taking a quick look at your code:
for (int i = 3; i < numfields; i++) {
if (dr[i].ToString() != "" && dr[i] != null){
r.Items.Add(new ListItem(dr[i].ToString(), dr[i].ToString()));
//r.SelectedIndexChanged += new EventHandler(rowSelectedIndex);
}
}
The most obvious thing that jumps out is your if statement. You should first check for null:
if (dr[i] != null && dr[i].ToString() != ""){
As if dr[i] is null, you'll get an exception (as you'll be trying to call the ToString() method on a null object.
If the contents of dr are always going to be strings, you might consider writing:
if(!String.IsNullOrEmpty(dr[i]){
I also note you start your indexing at 3 - is this because you want to skip the first 3 fields?
Wherever you create your variable, 'r', you can set the name and ID properties. You can use the ID property to look for the control on PostBack. So if you created your radiolist like so:
RadioButtonList r = new RadioButtonList();
r.Id = "MyRadioButtonList";
r.SelectedIndexChanged += MyRadioButton_SelectedIndexChanged;
Which would point at the following event handler:
private void MyRadioButton_SelectedIndexChanged(Object sender, EventArgs e) {
... Do Stuff ...
}
There are several ways of finding your control when you post back; you can look in the Request.Forms collection for a control matching the name of the control you submitted, or, more appropriately, you can use the FindControl method with the ID you gave the control. See C#, FindControl for a post with a method (by Jeff Atwood!) that will search the entire hierarchy of controls for your control.
When you add a dynamic control is important, too. If you add it too late in the page lifecycle then it will not be available on PostBack. See http://support.microsoft.com/kb/317515 for more details on just when to add a control. There are plenty of resources for Dynamic ASP.Net controls around too.
You could put your RadioButton into a list as you create them. This is also when you want to add your handlers.
RadioButton rb;
for (int i = 1; i < 5; i++)
{
rb = new RadioButton();
rb.AutoSize = true;
rb.Location = new System.Drawing.Point(25, (i*25) + 25);
rb.Name = "radioButton" + i.ToString();
rb.Text = "radioButton" + i.ToString();
//Add some event handler?
this.Controls.Add(rb);
lstRadioButton.Add(rb);
}
Whenever you want to know which one is selected you can do a foreach loop of your list and look if your RadioButton is checked.
foreach (RadioButton rButton in lstRadioButton)
{
if (rButton.Checked == true)
{
//Do something
}
}
You are maybe searching for TagName property if the programmatic name isn't enough for you.
The problem is that you are creating the controls in page_load. In order for their values to be posted back into the controls correctly, you must move this creation into the page_init method and recreate them every time.
Then, in page_load, you can access the values in the controls correctly. If you give them IDs using a consistent naming convention, you will be able to find them using the FindControl method or, in page_init, you can store them in a collection at the page or user control level.
I've got a form with multiple text boxes which are file paths for the program to import data from. Currently they are checked for non-zero length by the following:
//this code imports the files required by the user, as specified in the
//file path text boxes
private void btImport_Click(object sender, EventArgs e)
{
bool hasPath = false;
foreach (TextBox box in this.gbPaths.Controls.OfType<TextBox>().Where(tb => tb.Text.Length > 0))
{
hasPath = true;
//import code
}//end foreach
if (!hasPath)
{
MessageBox.Show("You must enter at least one file path.");
}//end if
}//end import code
What I'm wondering is can I replace the //import code part with something like:
if(tb.Name = "txtAvF") then...
or similar, or do I have to do it outside of the foreach loop? Thanks in advance. Let me know if I need to clarify anything.
If you want to check to see if the TextBox is one of the ones on the form (which I think you are), then you are == which (taken from MSDN)
the operator == tests for reference equality by determining if two references indicate the same object
So this is what you're looking for:
if(box == textBox1 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox1
}
else if(box == textBox2 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox2
}
else if (box == textBox3....)
You should do it inside of the loop. Like this:
if (box.Name == "txtAvF")
box.Text = "What you want";
But setting hasPath inside the loop just holds state for your last path. You should also move MessageBox code inside loop.
The hasPath assignment seems correct to me; it's set for any one text box, and if not set at the end of the loop, a message is displayed. This rhymes well with the text so displayed. Moving the MessageBox call into the loop would cause the dialog box to never be displayed (or errenously displayed), at least as the code is implemented now, since the OfType<>().Where() guarantees that all text boxes iterated over have at least some content.
(I would add this as a comment to #Xaqron but don't have the necessary reputation yet.)