Reputation: 1925
if(pictureBox1.Tag.ToString() == "accept")
{
char room1 = Convert.ToChar(lbl_roomid1.Text);
row1[13] = (byte)room1;
DateTime sdt1 = DateTime.Parse(txt_sdate1.Text);
//some code
}
if (pictureBox2.Tag.ToString() == "accept")
{
char room2 = Convert.ToChar(lbl_roomid2.Text);
row1[13] = (byte)room2;
DateTime sdt1 = DateTime.Parse(txt_sdate2.Text);
//some code
}
/* What if i wanted to type this code inside a loop?? i need to do the same for 10 pictureboxes */
Upvotes: 1
Views: 192
Reputation: 11
Loops to access form elements in c#.
I usually use something like this.
Let say i have 10 picturebox i name it picturebox1 - picturebox10.
Then Do a loop for the number to loop to 10 i use a variable no inside it put this code
String Picturebox = "picturebox" + no.ToString();
Control[] oControl = Controls.Find(Picturebox, true);
foreach(Control foundControl in oControl)
{
PictureBox foundControlA = foundControl as PictureBox;
foundControlA.(methods or property here) = (what you want to put to foundControlA)
}
If you have more controls accompanied by each control you can use the same method. The hint here is that i use the same naming convention on my elements or object in my winforms and loop the variable no according to what you want.
Upvotes: 0
Reputation: 7692
Something like this:
public void DoMagic(Label label, TextBox textBox)
{
//...
}
And this:
foreach (Control currentControl in this.Controls)
{
if (currentControl is PictureBox)
{
if (((PictureBox)currentControl).Tag.ToString().Equals("accept"))
{
string controlId = currentControl.Name.Remove(0, 11);
string labelName = string.Concat("lbl_roomid", controlId);
string txtName = string.Concat("txt_sdate", controlId);
this.DoMagic(this.Controls.Find(labelName, true)[0] as Label, this.Controls.Find(txtName, true)[0] as TextBox);
}
}
}
Regards
Upvotes: 4
Reputation: 169416
You could make an array of the elements.
The following is a little dirty, but...
class PBRoomDate {
// Helper data holder class. Could probably be an anonymous class in C# 4.0
public PictureBox PB;
public Label RoomLabel;
public TextBox DateText;
PBRoomDate(PictureBox PB, Label RoomLabel, TextBox DateText) {
this.PB = PB; this.RoomLabel = RoomLabel; this.DateText = DateText;
}
}
// [...]
var pbRoomDates = new PBRoomDate[]{
new PBRoomDate(pictureBox1, lbl_roomid1, txt_sdate1),
new PBRoomDate(pictureBox2, lbl_roomid2, txt_sdate2),
new PBRoomDate(pictureBox3, lbl_roomid3, txt_sdate3),
// etc.
};
foreach(var pbRoomDate in pbRoomDates) {
if(pbRoomDate.PB.Tag.ToString() == "accept") {
row1[13] = (byte)Convert.ToChar(pbRoomDate.RoomLabel.Text);
DateTime dt = DateTime.Parse(pbRoomDate.DateText.Text);
}
}
The cleaner solution would be to use a custom UserControl to contain the three elements per "picturebox" and lay those out. That would also be easier to maintain and more extendable should the need arise.
Upvotes: 2