String to existing object - c#

So i have my buttons like this :
text : Skarl, Name : btnHeroe1
text : Kled, Name : btnHeroe2
text : Kled, Name : btnHeroe3
My object are like this (price, damage)
Heroe Heroe1 = new Heroe(100,5);
Heroe Heroe2 = new Heroe(500,10);
Heroe Heroe3 = new Heroe(100,40);
They have properties (price,dps,level)
And when i click on my button, i use this method with these lines to get the name of the button pressed :
Button b = sender as Button;
string vButton = b.Name;
string strHeroeToBuy = vButton.Substring(3, vButton.Length - 3);
Now i'm asking. How can i get the properties like this : strHeroeToBuy.Price ?
Edit : Solved it by getting the id of my heroes and searching with button have the same id

If you keep your heroes in a list, and give them unique ids then you can find them:
// The id can be an int or a string, it's your choice
Heroes = new List<Heroe> {
new Heroe(id: 1, 100,5),
new Heroe(id: 2, 500,10),
new Heroe(id: 3, 100,40)
};
(...)
var id = //get Id from button
// needs 'using System.Linq'
var myHero = Heroes.FirstOrDefault( h => h.Id == id);
if(myHero == null) // error

One way to allow looking up an attribute would be to use a Dictionary, though it will require a unique key.
So, you would need to map your objects into the dictionary. Here is a sample console app to demonstrate:
using System;
using System.Collections.Generic;
namespace ConsoleApp
{
public class Hero
{
public Hero(int price, int points)
{
Price = price;
Points = points;
}
public int Price { get; set; }
public int Points { get; set; }
}
class Program
{
static void Main(string[] args)
{
var heros = new Dictionary<string, Hero>();
heros.Add("Hero1 Name", new Hero(10, 100));
heros.Add("Hero2 Name", new Hero(11, 101));
heros.Add("Hero3 Name", new Hero(12, 102));
if (heros.ContainsKey("Hero1 Name"))
{
Console.WriteLine(heros["Hero1 Name"].Price);
}
}
}
}

You could just store each hero in the .Tag() property of each button. Associate them in the Load() event of the form (assuming WinForms):
private Heroe Heroe1 = new Heroe(100,5);
private Heroe Heroe2 = new Heroe(500,10);
private Heroe Heroe3 = new Heroe(100,40);
private void Form1_Load(object sender, EventArgs e)
{
btnHeroe1.Tag = Heroe1;
btnHeroe2.Tag = Heroe2;
btnHeroe3.Tag = Heroe3;
}
Now you can just grab that hero from the tag:
Button b = sender as Button;
Heroe H = (Heroe)b.Tag;
// ... do something with "H" ...

You cannot do that for with a String. You could use the Tag-property on your Button to achieve it!

First you need a List of Heroes of some sort. This list need to be accessible from the form constructor, and from the click event.
public partial class Form1: Form
{
Hero[] data = new []{
new Hero{ Name= "Foo"},
new Hero{ Name= "Bar", Price=100, Dps=20, PropertyName=Value},
};
public Form1(){
// ...
}
// ...
}
At initialisation you will create the button based on your listing of heroes.
public Form1()
{
InitializeComponent();
// Have a Container that will hold the buttons
foreach(var hero in data){
var button = new Button();
//set text // set size
// set position. Compute it based on button size you just set.
// We put the whole hero in the tag not just the name `button.Tag = hero.Name`
button.Tag = hero;
// Add one even for all the button.
button.Click += new EventHandler(HeroButton_Click);
//Add button to the container
this.Controls.Add(button); // This or a container.
}
}
And the event that will be handle all the button click:
private void HeroButton_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
var hero = (Hero)btn.Tag
// Do thing with the Hero.
//Old Way, we search for the Hero in the list Data
// var hero = data.FirstOrDefault(x=> x.Name == (string)btn.Tag);
// if(hero==null) ; // error, could not find the hero
}

Related

Connecting a picture box being pressed to a certain letter

I have questions in my program that are jumbled up words and the user tries to un-jumble them. I want them to do this by them clicking multiple picture which have certain letters on it to form the word but I don't know how to connect the picture I have to a certain letter (e.g. Say I have a picture of the letter "a" how do I connect it so that the program knows when that picture is pressed the letter a is pressed).
This is the coding I have so far (to randomize the question and link the answers to it).
*Also I'm very new to coding so any suggestions please can you show what exactly to add/change to my code.
public partial class Level1 : Form
{
Random rnd = new Random(); //sets the random variable
List<string> strStrings = new List<string>() { "ZUZB", "HXAO", "MXAE", "KYCU", "CWEH", "PHIC", "HOCP", "SXIA", "ISHF", "KOJE" };//displays wprds om a list
Dictionary<string, string> dictStrings = new Dictionary<string, string>() //dictionary containing the word as the key, and the answer as the value in the key/value pair.
{
{ "ZUZB", "BUZZ" },
{ "HXAO", "HOAX" },
{ "MXAE", "EXAM" },
{ "KYCU", "YUCK" },
{ "CWEH", "CHEW" },
{ "PHIC", "CHIP" },
{ "HOCP", "CHOP" },
{ "SXIA", "AXIS" },
{ "ISHF", "FISH" },
{"KOJE", "JOKE" }
};
public Level1()
{
InitializeComponent();
}
int skip; //declares the skip variable
int score; //declares the score variable
int question; //decalres the question variable
private void nextButton_Click(object sender, EventArgs e)
{
if (strStrings.Count > 0)
{
string rndWord = strStrings[rnd.Next(0, strStrings.Count())];
lbljumble.Text = rndWord;
strStrings.Remove(rndWord);
}
else
{
lbljumble.Text = "No more questions!";
}
answerLabel.Text = ""; //randomly displays questions in the label until there are no more questions left to ask
score += 10; //add 10 to score and display in label
lblscore.Text = Convert.ToString(score);
question += 1; //add one to question number and display in label
lblqnum.Text = Convert.ToString(question);
tmrtime.Interval = (tmrtime.Interval) - 100; //amount of time taken after each question
}
private void answerButton_Click(object sender, EventArgs e)
{
string answer = (dictStrings.TryGetValue(lbljumble.Text, out answer)) ? answer : "";
answerLabel.Text = answer; //displays answer in label after the answer button is pressed to display the corresponding answer to the question
}
private void btnskip_Click(object sender, EventArgs e)
{
skip = 1; //skip equals 1
if (skip == 1) //of skip equals one
{
skip--; //take one from skip
lblskip.Text = " remaining: no"; //display that no skips are available
}
else
{
lblskip.Text = "No skips remaining"; //display no skips remaining
}
}
}
}
If I understand your question correctly you would like to know what letter was selected/clicked by the user.
You can dynamically create picture boxes, assign the .Name of the picture box to the value you would like the picture box to have then subscribe to the Click event for each picture box.
In the click event check the name of the sending picture box object sender. (you could alternatively use the pictureBx.Tag if you don't want to use the pictureBx.Name )
Here is an example form.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
lblAnswer.Text = "";
DrawLeters();
}
string checkAnswer = "check";
void DrawLeters()
{
this.SuspendLayout();
string[] alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".Split(",");
var pictureLocation = new Point(0, 0);
for (int i = 0; i < alphabet.Length; i++)
{
//Create a picture box
PictureBox pictureBx = new PictureBox();
//set the default location of the box (0,0) in this scenario
pictureBx.Location = pictureLocation;
//make the box 16 by 16
pictureBx.Size = new Size(16, 16);
//set the name of the box to that of the letter it represents
pictureBx.Name = alphabet[i];
//assign a click event to the box
pictureBx.Click += PictureBx_Click;
//now create the image that will fill the box
Image img = new Bitmap(16, 16);
using (Graphics graph = Graphics.FromImage(img))
{
graph.Clear(Color.White);
Brush textBrush = new SolidBrush(Color.Black);
graph.DrawString(pictureBx.Name, this.Font, textBrush, 0, 0);
graph.Save();
}
//assign the image to the box
pictureBx.Image = img;
//add the box to the form
this.Controls.Add(pictureBx);
//change the location for the next box
pictureLocation.X += 17;
if (i % 10 == 0 && i > 0)
{
pictureLocation.Y += 17;
pictureLocation.X = 0;
}
}
this.ResumeLayout(false);
this.PerformLayout();
}
private void PictureBx_Click(object sender, EventArgs e)
{ // assign the clicked value to the answer label
if (sender is PictureBox pbx)
lblAnswer.Text += pbx.Name;
}
private void checkAnswerBtn_Click(object sender, EventArgs e)
{
//check the answer
if (lblAnswer.Text == checkAnswer)
lblFeedback.Text = "Correct!!";
else
lblFeedback.Text = "NO!!";
}
private void clearBtn_Click(object sender, EventArgs e)
{
//clear the answer label
lblAnswer.Text = "";
}
}
and the result is this.
i'm just checking that the answer is check you would use your own logic to determine the correct answer.
You can add some picture-boxes and name them as Letter_a_pb, Letter_b_pb etc., create a Click event, and then create an if statement to check which pictureBox is clicked and if it equal to the letter 'a'.
For instance:
string question = "a";
private void Letter_a_pb_Click(object sender, EventArgs e)
{
if (question == "a")
MessageBox.Show("Excellent!");
else
MessageBox.Show("Try Again!");
}
Let me know if this is what you've searched for.

Combine Text cell & ComboBox cell to a TreeView column GTK C#?

I need to create a treeview column which contains both a text cell & Combobox cell.
I want to use a text cell if the value is one.
I want to use a Combobox cell if values are more than one.
Can you please share help link or sample on this.
Thanks!
Vijay
Created CellRenderComboBox object and Add this object to TreeviewColumn object.
The User need to register cellRendererCombo.EditingStarted += CellEditingStartedHandler event for updating combo box runtime.
using System;
using System.Threading;
using Gtk;
public partial class MainWindow : Gtk.Window
{
private Gtk.TreeView treeview1;
private int guiThreadId;
private bool stop = false;
private int threadId = 0;
public delegate void ThreadStart();
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
guiThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
// Create our TreeView
treeview1 = new Gtk.TreeView();
Gtk.ScrolledWindow scrolledWindow = new ScrolledWindow();
scrolledWindow.Add(treeview1);
Gtk.VBox vBox = new VBox();
vBox.Add(scrolledWindow);
this.Add(vBox);
CellRendererCombo cellRendererCombo = new CellRendererCombo();
Gtk.TreeViewColumn treeViewColumn = new TreeViewColumn();
treeViewColumn.Title = "TYPE";
treeViewColumn.PackStart(cellRendererCombo, false);
treeViewColumn.AddAttribute(cellRendererCombo, "text", 0);
cellRendererCombo.Editable = true;
cellRendererCombo.Model = new Gtk.ListStore(typeof(string));
cellRendererCombo.Mode = CellRendererMode.Editable;
cellRendererCombo.TextColumn = 0;
cellRendererCombo.HasEntry = false;
cellRendererCombo.WidthChars = 20;
cellRendererCombo.Style = Pango.Style.Normal;
cellRendererCombo.Edited += OnActionChanged;
cellRendererCombo.EditingStarted += CellEditingStartedHandler;
treeview1.AppendColumn(treeViewColumn);
Gtk.ListStore listStore = new ListStore(typeof(string));
listStore.AppendValues("A");
listStore.AppendValues("B");
}
protected void OnEdited(object sender, Gtk.EditedArgs args)
{
Gtk.TreeSelection selection = treeview1.Selection;
Gtk.TreeIter iter;
selection.GetSelected(out iter);
treeview1.Model.SetValue(iter, 1, args.NewText); // the CellRendererText
}
protected void CellEditingStartedHandler(object o, EditingStartedArgs args)
{
Console.WriteLine($"CellEditingStartedHandler");
if (o is Gtk.CellRendererCombo)
{
Gtk.CellRendererCombo cellRendererCombo = (Gtk.CellRendererCombo)o;
((Gtk.ListStore)cellRendererCombo.Model).Clear();
((Gtk.ListStore)cellRendererCombo.Model).AppendValues("A");
((Gtk.ListStore)cellRendererCombo.Model).AppendValues("B");
}
}
}

Advice on best way to resolve issue - C# Windows forms (list boxes, text box, user input)

I am new to C# and have started a program that I want to take in data from user, send to list box, sort list box and then save results. This happens via two text boxes:
txtUsername
txtResult
below the text box is a button that is disabled unless both text fields are entered, the button (btnAdd) adds the results and name of student to two separate list boxes:
lstUsername
lstResult
by disabling the button I ensure only both name and result are entered and sent to the list boxes in unison, the next bit is where it becomes tricky for me..
I want to be able to be able to sort the list boxes in ascending order to see at a glance the user with the highest result, but this wont be achieved due to the entries in each list box not being linked to one another. for example if a put a line of code to sort the high scores they then would not match the user in the list box parallel. I have only touched on arrays but understand the data between Username and result in a list box would need to be linked in some way so they are matched even after sorting.
This is the current code on the button that sends both the username and result to the list boxes:
InitializeComponent();
{
btnAdd.Enabled = !string.IsNullOrWhiteSpace(txtResult.Text);
btnAdd.Enabled = !string.IsNullOrWhiteSpace(txtUsername.Text);
}
private void btnAdd_Click(object sender, EventArgs e)
{
lstUsername.Items.Add(txtUsername.Text);
lstResult.Items.Add(txtResult.Text);
//There is also a counter that counts entries once being sent to the list
txtScoreCount.Text = lstUsername.Items.Count.ToString();
lstResult.Items.Count.ToString();
txtResult.Clear();
txtUsername.Clear();
txtUsername.Focus();
txtUsername.SelectAll();
}
If anyone can provide advice on how I am able to match the entries of two separate list boxes together I would be very grateful, I am also happy to provide more code if required. Any advice is beneficial to me. I will be able to work out saving the data and loading it back into the lists myself once I have the data in two lists bound, thank you.
This should get you somewhere.
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
namespace Students2
{
public partial class Form1 : Form
{
public class Student : ListViewItem
{
public Student(string name, float grade) : base()
{
this.Text = name;
//Add its grade as a subitem automatically.
this.SubItems.Add(new ListViewSubItem(this, grade.ToString()));
}
}
public class ListViewItemComparer : IComparer
{
private int ColIdx = 0;
public ListViewItemComparer(int index) { ColIdx = index; }
public int Compare(object x, object y)
{
switch(ColIdx)
{
case 1: //Numeric
{
var a1 = Convert.ToSingle(((ListViewItem)x).SubItems[ColIdx].Text);
var a2 = Convert.ToSingle(((ListViewItem)y).SubItems[ColIdx].Text);
return a1.CompareTo(a2);
}
default:
return String.Compare(((ListViewItem)x).SubItems[ColIdx].Text, ((ListViewItem)y).SubItems[ColIdx].Text);
}
}
}
public Form1()
{
InitializeComponent();
//Initialize ctrls
TextBox txtUsername = new TextBox();
TextBox txtGrade = new TextBox();
Button btnAdd = new Button();
ListView lBox = new ListView();
//POS
txtUsername.Location = new Point(0, 10);
txtGrade.Location = new Point(0, 40);
btnAdd.Location = new Point(0, 80);
lBox.Location = new Point(120, 0);
//ListView props
lBox.HeaderStyle = ColumnHeaderStyle.Clickable;
lBox.View = View.Details;
lBox.Size = new Size(200, 200);
//Modify the whole LView sorting so both are synced.
lBox.ColumnClick += new ColumnClickEventHandler((o, e) =>
{
lBox.ListViewItemSorter = new ListViewItemComparer(e.Column);
});
lBox.Columns.Add("Name");
lBox.Columns.Add("Grade");
this.Controls.Add(txtUsername);
this.Controls.Add(txtGrade);
this.Controls.Add(btnAdd);
this.Controls.Add(lBox);
btnAdd.Text = "Add";
//Add a new Student object upon click (Inherits from ListViewItem)
btnAdd.Click += new EventHandler((o, e) =>
{
try
{
lBox.Items.Add(new Student(txtUsername.Text, Convert.ToSingle(txtGrade.Text)));
lBox.Refresh();
}
catch (Exception ex)
{
MessageBox.Show("Incorrect input.");
}
});
}
}
}

Switching to dynamically created TabPage on button click

I'm practicing my coding and am trying to create a till by Dynamically prefill the items that are stored in a text file. I can dynamically create Tabs, Buttons and create menu buttons based on the categories of items. Where I'm struggling is I'm trying to switch the Tab on a button click. The Tabs are given a Name, which is the category ID, and the Text displays the category. In the event that trys to switch the tab I get the following error:
Error CS0266 Cannot implicitly convert type 'object' to 'System.Windows.Forms.TabPage'. An explicit conversion exists (are you missing a cast?)
I'm presuming that I need to Create a tab page or something, but I can't find out how to do this. Been on it for hours! Here's my code....
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
string[] loadedFile = File.ReadAllLines(#"h:\shopItemsV2.txt");
foreach (string line in loadedFile)
{
// Split string and create required variables
string[] newBtnData = line.Split(',');
int catID = int.Parse(newBtnData[0]);
string cat = newBtnData[1];
string item = newBtnData[2];
double price = double.Parse(newBtnData[3]);
// Create tab if needed
if (tabControl1.TabCount < catID)
{
TabPage tp = new TabPage()
{
Text = cat,
Name = catID.ToString()
};
tabControl1.TabPages.Add(tp);
// Add FlowLayoutPanel with unique name
FlowLayoutPanel fp = new FlowLayoutPanel()
{
Name = "fp" + catID.ToString(),
Dock = DockStyle.Fill
};
// Add FlowLayoutPanel to correct Tab
tabControl1.TabPages[catID-1].Controls.Add(fp);
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = catID,
Width = 100,
Height = 50,
Text = cat,
};
newMenuBtn.Click += SwitchTab;
menuFP.Controls.Add(newMenuBtn);
}
// Create Button
Button newBtn = new Button()
{
Name = item,
Tag = price,
Width = 100,
Height = 100,
Text = item,
};
newBtn.Click += AddItem;
//Add button to correct tab
foreach (TabPage tabP in tabControl1.TabPages)
{
if (tabP.Name == catID.ToString())
{
Control fp = this.Controls.Find("fp"+catID, true).First();
fp.Controls.Add(newBtn);
}
}
}
}
private void SwitchTab(object sender, EventArgs e)
{
// Create button, switch to required Tab
// Tabs named the same as Tag on the button
Button clickedBtn = sender as Button;
tabControl1.SelectedTab = clickedBtn.Tag;
}
}
Any help would be greatly appreciated.
You can store anything in the Tag() property of your button. With that in mind, store a reference to your TabPage!
Change:
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = catID,
Width = 100,
Height = 50,
Text = cat,
};
To:
// Create Button for menu
Button newMenuBtn = new Button()
{
Name = cat + "Btn",
Tag = tp; // store the reference to the TabPage you created
Width = 100,
Height = 50,
Text = cat,
};
Then the suggestion by Uwe Keim should work:
tabControl1.SelectedTab = clickedBtn.Tag as TabPage;
private void AddNewPr_Click(object sender, EventArgs e)
{
TabPage tab = new TabPage();
_list = new ListBox();
_list2 = new ListBox();
PictureBox picBox = new PictureBox();
picBox.Click = picBox_Click;
//More stuff here
//Add the controls
tabControl1.Controls.Add(tab);
tab.Controls.Add(list);
tab.Controls.Add(list2);
tab.Controls.Add(pictureBox);
}

How can I to manipulate dynamically created controls?

Lets say I have a form where someone can catalog a multiple people's Name and their State and City?
Assume I already have all the State/Cities in database. (a table for each state, with cities listed in each table)
The Name field will be a TextBox. And the State & City fields will be ComboBox (DropDownLists).
One row (for the entry of one person) already exists in the form. But I want the user to be able to dynamically add rows of entries by pressing an "Add Person" button.
The next step is where I'm struggling. In each dynamically added row of fields, I would like the second ComboBox (Cities) to be populated depending on which State is chosen in the first Combo Box. Also, the Cities ComboBox will remain disabled until the State ComboBox is chosen.
My code looks something like this:
public ComboBox cbState;
public ComboBox cbCities;
public static int NumberOfPeople = 1;
private void btnAddNewPerson_Click(object sender, EventArgs e)
{
NumberOfPeople++;
TextBox txtPerson = new TextBox();
txtPerson.Name = "Person" + NumberOfPeople;
Panel.Controls.Add(txtPerson);
// ADD State ComboBox
cbState = new ComboBox();
cbState.Name = "State" + NumberOfPeople;
cbState.Enabled = true;
cbState.DropDownStyle = ComboBoxStyle.DropDownList;
Panel.Controls.Add(cbState);
// ADD City ComboBox
cbCity = new ComboBox();
cbCity.Name = "City" + NumberOfPeople;
cbCity.DropDownStyle = ComboBoxStyle.DropDownList;
cbCity.Enabled = false;
cbCity.SelectedValueChanged += new System.EventHandler(this.ChangeState);
Panel.Controls.Add(cbCity);
}
private void ChangeState(object sender, EventArgs e)
{
..... Don't know how to properly identify the City ComboBox that is in the same row as the State ComboBox that was just changed, and manipulate/populate it.....
}
Anyone able to help me solve this issue??
I'd greatly appreciate it!!
You could use a dictionary
Dictionary<ComboBox,ComboBox> CityToStateMap = new Dictionary<ComboBox,ComboBox>();
then when you add a row
CityToStateMap[cbState] = cbCity;
then when you changestate
ComboBox city = CityToStateMap[(ComboBox)sender];
First of all I would create an additional class (e.g. with name Row) that contains all controls of one row. So you can encapsulate controls of one person in one object.
Your Form class gets a list member of such row objects like
List<Row> _rows = new List<Row>();.
In constructor of that class Row you create the controls of one row and assign the event handlers to the SelectedValueChanged event of the combobox controls.
You could use the Control.Tag in order to attach a data object to your controls. See how the controls are introduced to each other in the example.
private void btnAddNewPerson_Click( object sender, EventArgs e )
{
AddPersonRow();
}
private void AddPersonRow()
{
// Create combo boxes
ComboBox cbCity = new ComboBox();
ComboBox cbState = new ComboBox();
// Introduce them to each other
cbCity.Tag = cbState;
cbState.Tag = cbCity;
// ADD State ComboBox
cbState.Name = "State" + NumberOfPeople;
cbState.Enabled = true;
cbState.DropDownStyle = ComboBoxStyle.DropDownList;
cbState.SelectedValueChanged += new EventHandler( cbState_SelectedValueChanged );
panel.Controls.Add( cbState );
// Populate the states sombo
PopulateStateCombo( cbState );
// ADD City ComboBox
cbCity.Name = "City" + NumberOfPeople;
cbCity.DropDownStyle = ComboBoxStyle.DropDownList;
cbCity.Enabled = false;
cbCity.SelectedValueChanged += new EventHandler(cbCity_SelectedValueChanged);
panel.Controls.Add( cbCity );
}
void cbState_SelectedValueChanged( object sender, EventArgs e )
{
ComboBox cbState = sender as ComboBox;
ComboBox cbCity = cbState.Tag as ComboBox;
cbCity.Enabled = true;
// .. Go ahead and populate cbCity by cbState's selected value ..
}
void cbCity_SelectedValueChanged( object sender, EventArgs e )
{
// Up to you...
}
Note that instead of shaking hands with each other ComboBox, you could create a class that will hold both ComboBoxes, your TextBox control, the row number, etc. and then set the Tag of all these controls to the class itself.
public class PersonRow
{
public int RowNum { get; private set; }
public TextBox NameTextBox { get; private set; }
public ComboBox CityCombo { get; private set; }
public ComboBox StateCombo { get; private set; }
public PersonRow( int rowNum )
{
RowNum = rowNum;
// Create the controls
NameTextBox = new TextBox();
CityCombo = new ComboBox();
StateCombo = new ComboBox();
// Bind them to this instance
NameTextBox.Tag = this;
CityCombo.Tag = this;
StateCombo.Tag = this;
//.. continue as in the prev. example..
}
}
First of all you should find the name of the comboBox you want to manipulate.
then you can search a control in the panel which has the name we just found, then you can do what ever you want.
here is the code for that
private void ChangeState(object sender,EventArgs e){
ComboBox stateComboBox= (ComboBox)sender;
//find the name of target City ComboBox
string cityComboName = "City"+stateComboBox.Name.Substring(5); // 5 is the Length of 'State'
ComboBox cityComboBox=null;
foreach(Control cntrl in panel1.Controls){
if (cntrl.Name == cityComboName) {
cityComboBox= (ComboBox)cntrl;
break;
}
}
if (cityComboBox!= null) {
cityComboBox.Enabled = true;
// now you have the both cityComboBox and stateComboBox Of the same Row
}
}

Categories