creat eventHandler for label array element - c#

I was wondering how am I supposed to assign an eventHandler for each array element in my label array. I understand that it's not possible to create a method for each of eventHandlers, so what could be the solution? Thank you!
for(int i = 0, i < 10; i++)
{
lbs[i] = new Label();
lbs[i].Location = new System.Drawing.Point(76 + f, 164);
lbs[i].Size = new System.Drawing.Size(49, 17);
//able to perform this, but wont able to create a method for this
lbs[i].Click += new System.EventHandler(lbs[i]_Click);
}
//can't do this, what is alternative?
public void lbs[i]_Click(object sender, EventArgs e)
{
}

Your function name is invalid (you can't have [] in a function name) try changing lbs[i]_Click to lbs_Click.
for(int i = 0; i < 10; i++)
{
lbs[i] = new Label();
lbs[i].Location = new System.Drawing.Point(76 + f, 164);
lbs[i].Size = new System.Drawing.Size(49, 17);
lbs[i].Name = "label" + i;
//able to perform this, but wont able to create a method for this
lbs[i].Click += new System.EventHandler(lbsi_Click);
}
public void lbsi_Click(object sender, EventArgs e)
{
var label = sender as Label;
if(label != null && label.Name == "label1"){
//event was raised from label1
}
}

Related

Access Object created in another method C#

In this code I'm creating Few DataGridViews. Number of those depends on file which within each launch of application will be different, so is number of DataGridViews.
How can I Access particular dataGridView grid[i] and modify it from which event Form1_UserAddedRow was called in that method?
Code:
public void Form1_Load(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"..\..\Base.txt");
int diet_num = 0;
int grid_num = 0;
foreach (string x in lines) diet_num++;
grid_num = (diet_num / Constant.DATAGRID_DIETS_IN_GRID) + 1;
DataGridView[] grid = new DataGridView[grid_num];
for (int i = 0; i < grid_num; i++)
{
grid[i] = new DataGridView();
grid[i].Tag = i;
grid[i].Parent = this;
grid[i].Location = new Point(12, 12 + (8 + Constant.DATAGRID_ROW_HEIGHT * 2) * i);
grid[i].Visible = true;
grid[i].RowHeadersVisible = false;
grid[i].Height = Constant.DATAGRID_ROW_HEIGHT * 2;
grid[i].Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 3;
grid[i].UserAddedRow += Form1_UserAddedRow;
}
this.Width = Constant.DATAGRID_COLUMN_SIZE * Constant.DATAGRID_DIETS_IN_GRID + 40;
foreach (string x in lines)
{
DataGridViewColumn col = new DataGridViewTextBoxColumn();
col.Width = Constant.DATAGRID_COLUMN_SIZE;
col.HeaderText = x;
int colIndex = grid[0].Columns.Add(col);
}
}
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
//I want to access grid[i] and modify it here.
}
You should be able to cast the Sender object parameter in your event handler to the type of DataGridView to retrieve the grid which has been effected.
You are getting the DataGridViewRowEventArgs e as the argument to your event handler and thus you can access the Row property like
e.Row.Cells["somename"].Value = "some_value";
private void Form1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
var grid = sender as DataGridView;
if (grid == null) return;
//... do something
}

Declaring an Array of Textboxes

I'm trying to declare the array Scores as an array of textboxes. It doesn't have a size. I also need to declare it as an instance variable, and instantiate it in the method, CreateTextBoxes. I keep getting an error, "Scores is a field but is used like a type."
namespace AverageCalculator
{
public partial class AverageCalculator : Form
{
private TextBox[] Scores;
public AverageCalculator()
{
InitializeComponent();
}
private void AverageCalculator_Load(object sender, EventArgs e)
{
btnCalculate.Visible = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
int intNumTextBoxes;
intNumTextBoxes = Convert.ToInt32(txtNumScores.Text);
this.Height = 500;
btnCalculate.Visible = true;
btnOK.Enabled = false;
}
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
}
}
your CreateTextBoxes should probably be something like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
for (int i = 0; i < number; i++)
{
Scores[i] = new TextBox();
}
}
As Adil suggested, a List<TextBox> is probably better in this case.
You need to instantiate TextBox but number should be constant You can read more about the array creation expression here. Its better to use List instead of array if you want variable size.
Scores = new TextBox[number];
Using List
List<TextBox> Scores= new List<TextBox>();
Your code should read:
Scores = new TextBox[number];
// do things with this array
The problem is in
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
When you are trying to initialize the array, you are using the name of the field as they type and are including an index to the field name. Just change the new type to TextBox and remove the index accessor like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
replace line 1 with line 2
Scores[number] = new Scores[number];
Scores[number] = new TextBox();
You can't do this.
Scores[number] = new Scores[number];
Use a list of TextBox.

How can I use text property of dynamic created textfield?

I have this code, which dynamically creates some textfields for me. k is taken from user btw.
for (int i = 0; i < k; i++)
{
TextBox t1 = new TextBox();
t1.Parent = groupBox2;
t1.Left = textBox2.Left;
t1.Top = textBox2.Top + (i + 1) * 40;
t1.Name = "text" + (i + 1);
t1.Enabled = true;
groupBox2.Controls.Add(t1);
}
What i want to do is, after this creating phase is done, when the user presses groupbox2's "OK" button, I want to take the created textfields' text properties, but so far I don't know how could this be done, since I gave textfields a name, I tried this but didn't work.
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
node1.array[i] = Convert.ToInt32("text"+(i+1).Text);
}
}
Any help would be nice, thanks.
Try this method:
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
TextBox txtBox = (TextBox)groupBox2.FindControl("text" + (i + 1));
if (txtBox != null)
{
node1.array[i] = txtBox.Text;
}
}
}
Loop through your text boxes in groupBox1 and get their names,Try this:
List<string> TextBoxesName=new List<string>();
foreach (Control item in groupBox1.Controls)
{
if (item is TextBox)
{
TextBoxesName.Add((item as TextBox).Text);
}
}
Set to your dynamic texboxes ID and than you can do groupBox2.FindControl("dynamic_texbox_id") to get your text box
Easiest solution is to put your listboxes in a collection of some sort
List<ListBox> listboxes = new List<ListBox>();
for (...)
{
...
listboxes.add(listbox);
}
Then you can refer back to them whenever you want
Or since you're adding them to a groupbox, why not go through that collection?

C# checkbox

I have 3 check boxes in each row of 8 total rows. I want to have the third checkbox in each row to get checked only when the first two checkboxes are unchecked. I do not want to write a checkRow() method for each row.
What is the best way to go about it?
private void checkRow()
{
for (int i = 0; i < 8; i++)
{
var arraylist = new[] { checkbox1, checkbox2, checkbox3 };
if (checkbox1.Checked || checkbox2.Checked)
{
arraylist[2].Checked = false;
}
else
arraylist[2].Checked = true;
}
}
private void checbox1_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox2_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox3_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
In response.
private void checkRow()
{
var arraylist = new[] { checkEdit1, checkEdit2, checkEdit3 };
var arraylist1 = new[] { checkEdit4, checkEdit5, checkEdit6 };
var arraylist2 = new[] { checkEdit7, checkEdit8, checkEdit9 };
var array = new[] { arraylist, arraylist1, arraylist2 };
for (int i = 0; i < 8; i++)
{
//if checkedit1 or checkedit2 is checked the checkedit3 should not be checked
if (array[i]....Checked || array[i]....Checked)
{
arraylist[i]...Checked = false;
}
else
arraylist[i]...Checked = true;
}
}
I was trying to do something like this so that I dont have to write the checkRow() for each row
You should use the same method as the handler for all three delegates.
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox2.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox3.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
// do your stuff here
}
Assuming you're not using a DataGridView or other way of organizing them into logical rows, why don't you do the following:
Store the checkboxes in an array so you have easy access to them.
CheckBox[,] checkArray = new CheckBox[8,3]...
Store the row index in the Tag property of the first and second checkboxes.
checkBox01.Tag = 0;
checkBox02.Tag = 0;
checkBox11.Tag = 1;
checkBox12.Tag = 1;
Have all the first and second checkboxes point to the same event handler:
checkBox01.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox02.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox11.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox12.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
In the event handler, you now know exactly which check box to update and no longer have to loop:
private void aCheckBox_CheckedChanged(object sender, EventArgs e)
{
int rowIndex = (int)((CheckBox)sender).Tag;
checkArray[rowIndex,2].Checked = !(checkArray[rowIndex,0].Checked ||
checkArray[rowIndex,1].Checked);
}
You can also do this using string lookups with the checkbox name, but it is surely slower and is a pain to refactor later if you choose to rename the checkboxes.

How can I get the array index of a given object in C# with control arrays?

I am dynamically adding a bunch of controls to a form. Each control calls the same method, and in that method I need to know the array index of the the control that performed the action.
CheckBox[] myCB = new CheckBox[100];
int i;
for (i = 0; i < 100; i++)
{
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
tableLayoutPanel1.Controls.Add(myCB[i]);
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
label1.Text = sender.???array index property???.ToString();
}
So if I click myCB[42] label1 will read "42" Of course, if there is an easier way to handle dynamic controls I'd appreciate pointers.
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
label1.Text = Array.IndexOf(myCB, (CheckBox)sender).ToString();
}
Control's should have a Tag property. Maybe you can attach the index to the Tag. You will incur boxing though...
int j = i;
myCB[i].Click += delegate(object sender, EventArgs e) {
// here you can use "j"
};
One obvious solution would be to set the tag:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += new System.EventHandler(dynamicbutton_Click);
myCB[i].Tag = i;
tableLayoutPanel1.Controls.Add(myCB[i]);
}
Then:
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
Control control = (Control) sender;
label1.Text = sender.Tag.ToString();
}
Another alternative is to capture the information in the event handler, most simply using a lambda expression or anonymous method:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index = i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => label1.Text = index.ToString();
tableLayoutPanel1.Controls.Add(myCB[i]);
}
or for more complicated behaviour:
CheckBox[] myCB = new CheckBox[100];
for (int i = 0; i < myCB.Length; i++)
{
int index= i; // This is very important, as otherwise i will
// be captured for all of them
myCB[i] = new CheckBox();
myCB[i].Text = "Clicky!";
myCB[i].Click += (s, e) => DoSomethingComplicated(index, s, e);
tableLayoutPanel1.Controls.Add(myCB[i]);
}
(where you declare DoSomethingComplicated appropriately).

Categories

Resources