Dynamically Created Combobox's SelectedIndexChanged Event - c#

i'm designing a windows form application. In this app, user selects a number from a combobox, then depending on the number, some dynamic controls will be created(labels and comboboxes).
My problem is, i need to write some code on these dynamically created comboboxs' "selectedindexchanged" event. But i don't know how to create an event to dynamic combobox.
Here is my function:
FORM1.CS
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
for (int ix = pnl.Controls.Count - 1; ix >= 0; ix--)
if (pnl.Controls[ix].Name.Substring(0, 5) == "Child") pnl.Controls[ix].Dispose();
if (cmbb.SelectedIndex != 0)
{
Label[] childLabels = new Label[cmbb.SelectedIndex];
ComboBox[] txtTeamNames = new ComboBox[cmbb.SelectedIndex];
for (int i = 0; i < txtTeamNames.Length; i++)
{
//label create
var lbl = new Label();
childLabels[i] = lbl;
lbl.Name = "ChildLb" + i.ToString();
lbl.Text = (i + 1).ToString() + ". Çocuk-Yaş :";
lbl.Width = 80;
lbl.Location = new Point(cmbb.Location.X - 85, cmbb.Location.Y + 7 + ((i + 1) * 28));
lbl.Visible = true;
pnl.Controls.Add(lbl);
//combobox create
var cmb = new ComboBox();
txtTeamNames[i] = cmb;
cmb.Name = "Child" + i.ToString();
cmb.Location = new Point(cmbb.Location.X, cmbb.Location.Y + 5 + ((i + 1) * 28));
cmb.Width = 40;
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DataSource = ages.ToArray();
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}

You just register to the event like below...
cmb.SelectedIndexChanged += new System.EventHandler((object o, EventArgs e) =>
{
//Do something here
});
Or
cmb.SelectedIndexChanged += new System.EventHandler(cmb_SelectedValueChanged);
private void cmb_SelectedValueChanged(object sender, EventArgs e)
{
//Do something here.
}

You can hook up an event handler to the ComboBox like this:
cmd.SelectionChanged += new SelectionChangedEventHandler(GuiController_SelectionChanged);
void GuiController_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
throw new NotImplementedException();
}

Register event handler this way:
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
Unregister this way:
cmb.SelectedIndexChanged-=new EventHandler(cmb_SelectedIndexChanged);
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
{
//write your event code here
}
How to: Create Event Handlers at Run Time for Windows Forms
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
//// your code.....
//combobox create
var cmb = new ComboBox();
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
// remaining code
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
For specifying parameters - go through:
ComboBox.SelectedIndexChanged Event

Related

field with a button in the DataGridView

I have a bounded DataGridView. How can I add a button in one field with data? I will attach a screenshot of how I see it. Do you have any recommendations on this?
it's WinForms and I think that I need to write a custom column type.
I don't think the standard DataGridViewColumn subclasses provide what you're after.
It can be done, though: you will have to create your own custom Control (I guess a TextBox with a Button right next to it), and the appropriateDataGridViewColumn and DataGridViewCell subclasses to host your custom control.
Follow the documentation for further details.
Of course, the alternative would be using third-party, smarter grids.
Create custom column:
class TextAndButtonControl : UserControl
{
private TextBox textbox1;
private Button button1;
public TextAndButtonControl()
{
this.textbox1 = new TextBox();
this.Controls.Add(this.textbox1);
this.button1 = new Button();
this.Controls.Add(this.button1);
this.RenderControl();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi");
}
public string Text
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
public string ButtonText
{
get { return this.button1.Text; }
set { this.button1.Text = value; }
}
public void RenderControl()
{
this.textbox1.Location = new Point(0, 0);
this.textbox1.Width = 2 * this.Width / 3;
this.textbox1.Height = this.Height;
this.button1.Location = new Point(2 * this.Width / 3, 0);
this.button1.Width = this.Width / 3;
this.button1.Height = this.Height;
}
}
Add the control in the following way
private void Form1_Load(object sender, EventArgs e)
{
TextAndButtonControl bcol = new TextAndButtonControl();
bcol.Text = "Button Column ";
bcol.ButtonText = "Click Me";
bcol.Name = "btnClickMe";
bcol.RenderControl();
dgMainGrid.Controls.Add(bcol);
}
There is a DataGridViewButtonColumn-Type (Or if you just want a single Cell as Button -> DataGridViewButtonCell-Type).
You could create the DataGridButtonColumn and then add it to your DataGridView:
DataGridViewButtonColumn tempBtnColumn = new DataGridViewButtonColumn();
tempBtnColumn.HeaderText = "Button";
tempBtnColumn.Text = "Button-Text";
tempBtnColumn.Name = "Button-Name";
tempBtnColumn.UseColumnTextForButtonValue = true;
Grid.Columns.Add(tempBtnColumn);
//or if you want a specified position for the Grid:
Grid.Columns.Insert(0, tempBtnColumn);
Update
Here is an update, you could give the ButtonCell the Value you want and then read that with CurrentCell.Value (here is a example, hope it's understandable):
private void ButtonCellWithValue()
{
DataGridViewButtonCell dgvbc = new DataGridViewButtonCell();
dgvbc.Value = "1";
DataGridViewRow dgvr = new DataGridViewRow();
dgvr.Cells.Add(dgvbc);
dataGridView1.Rows.Add(dgvr);
dgvbc = new DataGridViewButtonCell();
dgvbc.Value = "2";
dataGridView1.Rows[0].Cells[1] = dgvbc;
GridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
}
void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (((DataGridView)sender).CurrentCell.Value == "1")
{
MessageBox.Show("Super");
}
else if (((DataGridView)sender).CurrentCell.Value == "2")
{
MessageBox.Show("Better");
}
}
Thank a lot #RavirajPalvankar.
If somebody will need, I will write the code here, because cann't write it to Ravuraj's comment, because it's long:
Use the class as Raviraj write:
class TextAndButtonControl : UserControl
{
private TextBox textbox1;
private Button button1;
public TextAndButtonControl()
{
this.textbox1 = new TextBox();
this.Controls.Add(this.textbox1);
this.button1 = new Button();
this.Controls.Add(this.button1);
this.renderControl();
this.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click! The value is:" + this.Text);
}
public string Text
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
public string ButtonText
{
get { return this.button1.Text; }
set { this.button1.Text = value; }
}
public void renderControl()
{
this.textbox1.Location = new Point(0, 0);
this.textbox1.Width = 2 * this.Width / 3;
this.textbox1.Height = this.Height;
this.button1.Location = new Point(2 * this.Width / 3, 0);
this.button1.Width = this.Width / 3;
this.button1.Height = this.Height;
}
}
then in main Form:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
for (int j = 0; j < 20; j++)
{
dt.Rows.Add("col1" + j.ToString(), "col2" + j.ToString());
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].Width = 150;
this.txbtnControl = new TextAndButtonControl();
this.txbtnControl.Visible = false;
this.dataGridView1.Controls.Add(this.txbtnControl);
//Handle the cellbeginEdit event to show the usercontrol in the cell while editing
this.dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
TextAndButtonControl txbtnControl;
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex > -1 && e.RowIndex != this.dataGridView1.NewRowIndex)
{
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
this.txbtnControl.Location = rect.Location;
this.txbtnControl.Size = rect.Size;
this.txbtnControl.Text = this.dataGridView1.CurrentCell.Value.ToString();
this.txbtnControl.ButtonText = "...";
this.txbtnControl.renderControl();
this.txbtnControl.Visible = true;
}
}

Add a mouse click event to generated Textbox fields

Any idea how to add a mouse click event to generated Textbox fields. Here is the code for generating TextBox fields:
private void button1_Click(object sender, EventArgs e)
{
TextBox textbox = new TextBox();
textbox.Location = new Point(60, 25 * count);
textbox.Size = new Size(301, 20);
textbox.Name = "textbox_" + (count + 1);
textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
panel1.Controls.Add(textbox);
count++;
if (count == 4)
{
MessageBox.Show("");
button1.Enabled = false;
}
}
The code below must be in the method that handles the mouse click event for every generated Textbox field:
TextBox txtName = (TextBox)this.Controls.Find("textbox_1", true)[0];
TextBox txth = (TextBox)this.Controls.Find("textbox_2", true)[0];
if (txtName != null)
{
}
I think you are looking for something like this:
int count = 0;
private void button1_Click(object sender, EventArgs e)
{
TextBox textbox = new TextBox();
textbox.Location = new Point(60, 25 * count);
textbox.Size = new Size(301, 20);
textbox.Name = "textbox_" + (count + 1);
textbox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TextBox_MouseClick);
textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
panel1.Controls.Add(textbox);
count++;
if (count == 4)
{
MessageBox.Show("");
button1.Enabled = false;
}
}
private void TextBox_MouseClick(object sender, MouseEventArgs e)
{
TextBox txtName = (TextBox)this.Controls.Find("textbox_1", true)[0];
TextBox txth = (TextBox)this.Controls.Find("textbox_2", true)[0];
if (txtName != null)
{
MessageBox.Show("Test");
}
}
When I preform a click on a TextBox this MessageBox window appears:
I would also change the TextBox_MouseClick method to :
private void TextBox_MouseClick(object sender, MouseEventArgs e)
{
Control[] txtName = this.Controls.Find("textbox_1", true);
Control[] txth = this.Controls.Find("textbox_2", true);
if ((TextBox)txtName[0] != null)
{
MessageBox.Show("Test");
}
}
Because if you create only one TextBox and perform a click on it you will get a System.IndexOutOfRangeException because the second TextBox isn't created so the array that holds you second TextBox is empty.

Adding Event Handler for Dynamically Created to window Form

I have a window form where I am creating a list of Checkboxes. The number of checkboxes created are based upon how many items are returned from the database. I've been able to create the checkboxes; however, I am not sure how to add event handlers for these checkboxes. For example, I'd like to add an OnCheckedChanged or CheckStateChanged event. How can I add these events? Also, I would appreciate any other suggestion. I am a total newbie to programming.
private void Form1_Load(object sender, EventArgs e)
{
CheckBoxes = new CheckBox[listGroup.Count()];
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i]+"_CheckedChanged");
CheckBoxes[i].Width = 200;
if (i == 0)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 10);
}
else if (i == 1)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 40);
}
else if (i == 2)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 80);
}
this.Controls.Add(CheckBoxes[i]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//...
CheckBoxes[i].CheckedChanged += checkBoxes_CheckedChanged;
CheckBoxes[i].CheckStateChanged += checkBoxes_CheckStateChanged;
}
void checkBoxes_CheckedChanged(object sender, EventArgs e)
{ //do stuff when checked changed }
void checkBoxes_CheckStateChanged(object sender, EventArgs e)
{ //do stuff when check state changed }
Note: this will give identical event handling for all of your checkboxes.
If you want to do different things for different textboxes, you have to name the eventhandler differently and define that eventhandler.
A more efficient way to set the location of your checkboxes
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i] + "_CheckedChanged");
CheckBoxes[i].Width = 200;
//set location based on index of i
CheckBoxes[i].Location = new System.Drawing.Point(5, 10 + (i * 30));
this.Controls.Add(CheckBoxes[i]);
}
private void LoadNewCheckboxes()
{
dynamic listGroupCount = 10;
List<System.Windows.Forms.CheckBox> CheckBoxes = new List<System.Windows.Forms.CheckBox>();
for (int i = 0; i <= listGroupCount - 1; i++)
{
System.Windows.Forms.CheckBox chkbox = new System.Windows.Forms.CheckBox();
chkbox.Text = i.ToString();
//listGroup.ElementAt(i).GroupName
chkbox.Name = "txt" + i.ToString();
//listGroup.ElementAt(i).GroupName.Replace(" "c, "_"c)
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox.CheckStateChanged += new EventHandler(chkbox_CheckStateChanged);
chkbox.Width = 200;
chkbox.AutoSize = true;
this.Controls.Add(chkbox);
CheckBoxes.Add(chkbox);
if (i == 0)
{
chkbox.Location = new System.Drawing.Point(5, 10);
}
else
{
chkbox.Location = new System.Drawing.Point(5, (CheckBoxes[i - 1].Top + CheckBoxes[i - 1].Height + 10));
}
}
}
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckedChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}
private void chkbox_CheckStateChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckStateChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}

Array of buttons: change property

I have an array of buttons, like this:
int x = 0, y = 0;
butt2 = new Button[100];
for (int i = 0; i < 100; i++)
{
butt2[i] = new Button();
int names = i;
butt2[i].Name = "b2" + names.ToString();
butt2[i].Location = new Point(525 + (x * 31), 70 + (y * 21));
butt2[i].Visible = true;
butt2[i].Size = new Size(30, 20);
butt2[i].Click += new EventHandler(butt2_2_Click); //problem lies here (1)
this.Controls.Add(butt2[i]);
}
private void butt2_2_Click(object sender, EventArgs e)
{
// want code here
}
I want to change the back color of the button when clicked. I was thinking of passing i to be able to do this:
butt2[i].BackColor = Color.Green;
This should do the trick:
private void butt2_2_Click(object sender, EventArgs e)
{
Button pushedBtn = sender as Button;
if(pushedBtn != null)
{
pushedBtn.BackColor = Color.Green;
}
}
And this holds for most UI events, the 'object sender' parameter refers to the control that 'sent'/'fired' the event.
To learn more about C# event handling, I would start here.
Also, here is a SO question about GUI event handling, answered nicely by Juliet (accepted answer).
Hope this helps.

Assign MouseHover event to newly created Control

This is the new control add code part:
for (int i = 0; i < 1; i++)
{
var newLabel = new Label();
newLabel.Location = new Point(x, y);
newLabel.Size = new System.Drawing.Size(25, 25);
newLabel.Name = "lbl" + realpocsed.ToString();
if (value2== "Value2")
{
newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
}
if (value== "Value1")
{
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseHover);
}
panel1.Controls.Add(newLabel);
The MouseHover event look like this:
private void MyControl_MouseHover(object sender, MouseEventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", X); // X should be name of the newly created label
}
May I ask if is there any way to assign the newly created with name "lbl" + realpocsed.ToString() instead of X?
Thank you for your time.
You're assigning a MouseDown event to your MouseHover code, not sure you want that.
It should look like this:
newLabel.MouseHover += MyControl_MouseHover;
For your X, you would have to cast the sender:
ToolTip1.Show("Hover Message Here", (Label)sender);
You can't access any object by creating its name in string. The simple way to do that is to pass the object reference:
ToolTip1.Show("t", (sender as Label));
Inside for:
newLabel.MouseHover += delegate (object sender, EventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", newLabel);
};
Update:
if (value == "Value1")
{
newLabel.MouseHover += delegate (object sender, EventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", newLabel);
};
}

Categories

Resources