Change Button Text - Windows Phone 7 - c#

How do you change the text of a button in Windows Phone 7 and C#? NullPointer Exception too, if I am doing the changing of the button text right, what is the problem?
public void CreateWords(Word[] theWords)
{
listOfWords = new Button[theWords.Length]; //Button Array
textBlock1.Text = theWords[0].getWord(); //Totally Works
for (int i = 0; i < theWords.Length; i++)
{
listOfWords[i].Content = theWords[0].getWord(); //NullPointer Exception
}
for (int i = 0; i < theWords.Length; i++)
{
stackWords.Children.Add(listOfWords[i]);
}
}

You're getting the NullReferenceException because, while you have created the new Button array, you haven't initialized any of the elements of that array (each element is still null).

As Justin said earlier, you have just created an Array of the Type of Button, You have not added any Button's to the Array as of yet. You need to explicitly set each index of the Array to a Button: Try doing something like this.
for (int i = 0; i < theWords.Length; i++)
{
listOfWords[i] = new Button();
listOfWords[i].Content = theWords[0].getWord(); //NullPointer Exception
}

Related

dynamically created labels overlap each other

I want to create labels that will follow one another. I have a grid name WordTemplateLayout to which I want to add the labels. I add them dynamically on the wpf window constructor after InitializeComponent() is called. Here is the method creating the labels:
private void CreateWordTemplate()
{
IList<char> template = CurrentGame.Template;
double widthPerBox = WordTemplateLayout.Width / template.Count;
//template.Count being a number, irrelevant to the question
for (int i = 0; i < template.Count; i++)
{
var templateVisual = new Label();
templateVisual.Name = "c" + i;
templateVisual.Width = widthPerBox;
templateVisual.Height = WordTemplateLayout.Height;
templateVisual.Background = new SolidColorBrush(Colors.Aqua);
WordTemplateLayout.Children.Add(templateVisual);
}
}
the problem being, that what actually appends is that instead of the labels lining up one after the other, they overlap each other:
The aqua box is all the labels overlap each other
so what I am asking, is how can I make the labels line up (horizontally) instead of to overlap?
As others have pointed out, you're better off using a StackPanel, or learning how to use viewmodels and data binding. Having said that, to answer your direct question, here's how you'd do it programmatically.
**NOTE: Ignore the 5 that I'm passing in to the methods, and instead use your template.Count. This is was just for me to get it to work on my end.
public MainWindow()
{
InitializeComponent();
CreateGridLayout(5);
CreateWordTemplate(5);
}
// Define the Grid layout
// If you want the labels to follow one another horizontally, define columns.
// If you want them stacked vertically, instead define rows.
private void CreateGridLayout(int count)
{
for (int i = 0; i < count; i++)
{
WordTemplateLayout.ColumnDefinitions.Add(new ColumnDefinition());
}
}
private void CreateWordTemplate(int count)
{
double widthPerBox = WordTemplateLayout.Width / 5;
for (int i = 0; i < 5; i++)
{
var templateVisual = new Label();
templateVisual.SetValue(Grid.ColumnProperty, i); // SET YOUR COLUMN HERE!
templateVisual.Name = "c" + i;
templateVisual.Width = widthPerBox;
templateVisual.Height = WordTemplateLayout.Height;
templateVisual.Background = new SolidColorBrush(Colors.Aqua);
templateVisual.Content = templateVisual.Name;
WordTemplateLayout.Children.Add(templateVisual);
}
}
you need to use another layout so the new elements will get in normal order. try stackPanel.
you can use grid and give each new label Row=index.
you can give each new label margin, like newLabel.margin-top = index*50

Create Button Array

I have 25 buttons on winform.I want add buttons to array with this way :
**Button btn =(Button)(this.Controls.Find("button"+i,true)[0]);** //this is hint
I tried this but it didnt work.When ı changed index [0] at the end of code ı get out of range exception:
Button[] button = new Button[25];
for(int i = 0; i < 25; i++)
{
button[i] = (Button)(this.Controls.Find("button" + i, true)[0]);
}
How can ı use this hint ?
Try to change the index of your for loop and re-test. As stated by ViperLiu in comment, the reason of out-of-index error is because the button is named automatically by Visual Studio starting from "button1"
Button[] button = new Button[25];
for(int i = 0; i < 25; i++)
{
button[i] = (Button)(this.Controls.Find("button" + (i + 1), true)[0]);
}

DGV doesn't update value

I Inerted a DGV called MarksDGV1 into my application while each cell inside of it has a default value of "0". So, after the user changes the value of some of them, when I try to reach the value for the last edited cell it gives me 0 instead of what the user typed even though it's shown correctly
(Please note: the unselected cells -which doesn't appear in Blue color- show value correctly)
How could I fix that?
Here is my code:
MarksDGV1.Refresh();
MessageBox.Show(MarksDGV1.Rows[0].Cells[1].Value.ToString());
And this is How I built the DGV:
using (DataGridViewTextBoxColumn tmp = new DataGridViewTextBoxColumn())
{
tmp.Width = 90;
tmp.ReadOnly = true;
tmp.HeaderText = "פרק מס.";
MarksDGV1.Columns.Add(tmp);
}
for (int i = 1; i <= 30; i++)
{
using (DataGridViewTextBoxColumn tmp = new DataGridViewTextBoxColumn())
{
tmp.Width = 50;
tmp.HeaderText = "שאלה מס." + i;
MarksDGV1.Columns.Add(tmp);
}
}
for (int i = 0; i < 8; i++)
{
using (DataGridViewRow tmp = (DataGridViewRow)MarksDGV1.Rows[i].Clone())
{
tmp.Cells[0].Value = i + 1;
for (int j = 1; j <= 30; j++)
{
tmp.Cells[j].Value = 0;
//tmp.Cells[j].Value = CurrentExam.Psy[i].Answers[j - 1];
}
MarksDGV1.Rows.Add(tmp);
}
}
Update: I tried typing DataGridView.Refresh(); but didn't work!
Update2: I was able to fix this by selecting another cell -different from the one that I'm concerned in- before I get the values. But that's not a solution for me
From the comments, you are using a button that doesn't take the focus away from the grid, so it remains in edit mode. Try it like this:
MarksDGV1.EndEdit();
MessageBox.Show(MarksDGV1.Rows[0].Cells[1].Value.ToString());

C# display components based on name

Is it possible to set a components visible attribute based on its name?
I have 12 "master" components (comboboxes) if you want to call them that and based on the selection in these I want to display anywhere from 1 to 16 textboxes. These are named in numeric order such as combobox1_textbox_0, combobox1_textbox_1 and so on. What I would like to do ideally is take the index of the combobox and pass it as a parameter to a method that sets the textboxes visible attribute to visible/hidden depending on the index passed into the method.
Is this possible? in pseudocode or what you call it I would like it to work something like this:
private void methodToSetVisibleAttribute(int indexFromMainComboBox)
{
for(int i = 0; i < 15; i++)
{
if(i < index)
{
combobox1_textbox_+i.Visible = true;
}
else
{
combobox1_textbox_+i.Visible = false;
}
}
}
I could do panels or something for the choices but seeing as all the selections from the combobox will use the same textboxes but in different amounts it seems like alot of work to make a panel for every possible selection not to mention difficult to expand the program later on.
Assuming you are using Windows Forms and not WPF, you can use ControlCollection.Find() to find controls by name:
var textBox = this.Controls.Find(string.Format("combobox1_textbox_{0}", i), true).OfType<ComboBox>().FirstOrDefault();
if (textBox != null)
textBox.Visible = (i < index);
else
Debug.Assert(false, "textbox not found"); // Or throw an exception if you prefer.
I'll suggest an alternative to your approach, maybe not quite what you're looking for:
Place your combo boxes in a List<ComboBox> and you can access them by an index number.
List<ComboBox> myCombos = new List<ComboBox>();
for (int i = 0; i < 16; i++)
{
ComboBox cb = new ComboBox();
//do what ever you need to do here. Set its location, add items, etc.
Form1.Controls.Add(cb); //Alternatively add it to another container.
myCombos.Add(cb); //Now it's in a list.
}
Modify them like this:
for(int i = 0; i < 15; i++)
{
if(i < index)
{
myCombos[i].Visible = true;
}
else
{
myCombos[i].Visible = false;
}
}
Or even more succintly:
for(int i = 0; i < 15; i++)
{
myCombos[i].Visible = i < index;
}

Setting the SelectedIndex on ComboBox

I am in a beginning C# class and I am having trouble figuring out why after the following code runs, the selected index is still -1 (i.e. the combobox at load is empty). It should be defaulting to selectedIndex = 1:
public string[,] GetArray()
{
//create array with conversion values
string[,] conversionInfo = { {"Miles","Kilometers", "1.6093"},
{"Kilometers","Miles", ".6214"},
{"Feet","Meters", ".3048"},
{"Meters","Feet","3.2808"},
{"Inches","Centimeters", "2.54"},
{"Centimeters","Inches",".3937"}};
return conversionInfo;
}
private void Form_Load(object sender, EventArgs e)
{
//get array to use
string[,] conversionChoices = GetArray();
//load conversion combo box with values
StringBuilder fillString = new StringBuilder();
for (int i = 0; i < conversionChoices.GetLength(0); i++)
{
for (int j = 0; j < conversionChoices.GetLength(1) - 1; j++)
{
fillString.Append(conversionChoices[i, j]);
if (j == 0)
{
fillString.Append(" to ");
}
}
cboConversion.Items.Add(fillString);
fillString.Clear();
}
//set default selected value for combobox
cboConversion.SelectedIndex = 0;
}
public void cboConversions_SelectedIndexChanged(object sender, EventArgs e)
{
LabelSet(cboConversion.SelectedIndex);
}
public void LabelSet(int selection)
{
//get array to use
string[,] labelChoices = GetArray();
//set labels to coorespond with selection
string from = labelChoices[selection, 0];
string to = labelChoices[selection, 1];
lblFrom.Text = from + ":";
lblTo.Text = to + ":";
}
This is a class assignment so I am not allowed to set anything using the designer, other than to link methods to event. Everything works correctly except for the default for the combobox.
Your code is completely correct, but you have one single fault in your mind. Consider, that you are loading the items into the ComboBox after you have initialized the control. At this point the control have no items, therefore the property "Text" is not setted automatically.
You have to differ between the SelectedIndex, which is the index of the item in the list of items, and the Text, which is the text, shown in the ComboBox. So think about when and how you should set the Text-property of the ComboBox.
Always set the Text-property to the first value of your item-list, after you changed it.
Greetings,
the answer of Mario can be interpreted also as:
put your code after the loading (example: on the shown event), in this way the control is initialized and has items.

Categories

Resources