Create Button Array - c#

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]);
}

Related

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());

How to access labels from loop and change their text

I have list where are 6 sentences which I want to put in 6 different labels.
All six labels are named Slot0Sentence, Slot1Sentence, Slot2Sentence...
This is how I loop
for (int i = 0; i < ls.Count; i++)
{
Slot0Sentence.Text = ls[i];
}
However I dont know how to access other labels.
If there would be normal string I would do Slot + i + Sentence but in this case this dont work.
with an array of labels you can control their properties. you don't need design here, you can do that with code.
Label[] l = new Label[6];
int x = 20;
for (int i = 0; i < l.Length; i++)
{
l[i] = new Label();
l[i].Name = "Hello " + i.ToString();
l[i].Text = "Hello " + i.ToString();
l[i].Location = new Point(x, 10);
x += 100;
}
you can change the names and text to whatever you like.
I'd just use Children property of parent container (Grid, StackPanel,..). This gives you a collection which supports indexes. Additionally, in case you have different controls, use if statement
if(element in Label)
{
element.Text = ...
}

How do I find and use a programatically-created control?

I've created a number of buttons on a form based on database entries, and they work just fine. Here's the code for creating them. As you can see I've given them a tag:
for (int i = 0; i <= count && i < 3; i++)
{
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Tag = i;
this.Controls.Add(btnAdd);
}
I use these buttons for visualising a polling system. For example, I want the button to be green when everything is fine, and red when something is wrong.
So the problem I'm running into is referencing the buttons later so that I can change their properties. I've tried stuff like the following:
this.Invoke((MethodInvoker)delegate
{
// txtOutput1.Text = (result[4] == 0x00 ? "HIGH" : "LOW"); // runs on UI thread
Button foundButton = (Button)Controls.Find(buttonNumber.ToString(), true)[0];
if (result[4] == 0x00)
{
foundButton.BackColor = Color.Green;
}
else
{
foundButton.BackColor = Color.Red;
}
});
But to no avail... I've tried changing around the syntax of Controls.Find() but still have had no luck. Has anyone encountered this problem before or know what to do?
If you name your buttons when you create them then you can find them from the this.controls(...
like this
for (int i = 0; i <= count && i < 3; i++)
{
Button btnAdd = new Button();
btnAdd.Name="btn"+i;
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Tag = i;
this.Controls.Add(btnAdd);
}
then you can find it like this
this.Controls["btn1"].Text="New Text";
or
for (int i = 0; i <= count && i < 3; i++)
{
//**EDIT** I added some exception catching here
if (this.Controls.ContainsKey("btn"+buttonNumber))
MessageBox.Show("btn"+buttonNumber + " Does not exist");
else
this.Controls["btn"+i].Text="I am Button "+i;
}
Put these buttons in a collection and also set the name of the Control rather than using its tag.
var myButtons = new List<Button>();
var btnAdd = new Button();
btnAdd.Text = dataTable.Rows[i]["deviceDescription"].ToString();
btnAdd.Location = new Point(x, y);
btnAdd.Name = i;
myButtons.Add(btnAdd);
To find the button use it.
Button foundButton = myButtons.Where(s => s.Name == buttonNumber.ToString());
Or Simply
Button foundButton = myButtons[buttonNumber];
In your case I would use a simple Dictionary to store and retrieve the buttons.
declaration:
IDictionary<int, Button> kpiButtons = new Dictionary<int, Button>();
usage:
Button btnFound = kpiButtons[i];
#Asif is right, but if you really want to utilize tag you can use next
var button = (from c in Controls.OfType<Button>()
where (c.Tag is int) && (int)c.Tag == buttonNumber
select c).FirstOrDefault();
I'd rather create small helper class with number, button reference and logic and keep collection of it on the form.

Change Button Text - Windows Phone 7

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
}

C# need to dynamically create radio buttons and determine which value user selected in Winform

I need to dynamically create radio buttons based on dynamic list. Scenario is like I have list of files shown as Radio button in WinForm. A user clicks on radio button to select file and move forward.
I tried doing following as an example
for (int i = 0; i < 10; i++)
{
ii = new RadioButton();
ii.Text = i.ToString();
ii.Location = new Point(20, tt);
tt = tt + 20;
panel1.Controls.Add(ii);
}
The problem is how would I check which value got selected by user?
A simple way to do it is by using the RadioButtons CheckChanged event to set a variable that specifies the file that they have chosen by using the RadioButtons text or Tag property which you could set to be the file itself?
e.g.
private File f = null;
for (int i = 0; i < 10; i++)
{
ii = new RadioButton();
ii.Text = i.ToString();
ii.Location = new Point(20, tt);
ii.Tag = fileArray[i]; // Assuming you have your files in an array or similar
ii.CheckedChanged += new System.EventHandler(this.Radio_CheckedChanged);
tt = tt + 20;
panel1.Controls.Add(ii);
}
private void Radio_CheckedChanged(object sender, EventArgs e)
{
RadioButton r = (RadioButton)sender;
f = (File)r.Tag;
}
It's certainly not the most elegant way but it would work.

Categories

Resources