Get values of dynamically created controls (comboboxes) - c#

I've got panel on which by default are two comboboxes and one "+" button which creates two new combo boxes bellow the first one, I can create multiple (n) rows with two combo boxes and everything is working, I just can't figure out how to get values of those boxes?
Here's code for creating (adding) controls
private void btnCreateFilter_Click(object sender, EventArgs e)
{
y += comboBoxHeight;
ComboBox cb = new ComboBox();
cb.Location = new Point(x, y);
cb.Size = new Size(121, 21);
panelFiltri.Controls.Add(cb);
yDrugi += comboBoxHeight;
ComboBox cbSql = new ComboBox();
cbSql.Location = new Point(xDrugi, yDrugi);
cbSql.Size = new Size(121, 21);
panelFiltri.Controls.Add(cbSql);
btnCancel.Location = new Point(btnCancel.Location.X, btnCancel.Location.Y + 25);
btnSaveFilter.Location = new Point(btnSaveFilter.Location.X, btnSaveFilter.Location.Y + 25);
}
And here's code where I'm lost:
private void btnSaveFilter_Click(object sender, EventArgs e)
{
int i;
foreach (Control s in panelFiltri.Controls)
{
//GOT LOST
}
}

You can get the text in the ComboBox as
private void btnSaveFilter_Click(object sender, EventArgs e)
{
foreach (Control control in panelFiltri.Controls)
{
if (control is ComboBox)
{
string valueInComboBox = control.Text;
// Do something with this value
}
}
}

I don't really know what you're trying to achieve... Maybe this will help you along...
private void btnSaveFilter_Click(object sender, EventArgs e)
{
foreach (ComboBox comboBox in panelFiltri.Controls)
{
var itemCollection = comboBox.Items;
int itemCount = itemCollection.Count; // which is 0 in your case
}
}

Related

Dynamically created combobox SelectedIndexChanged not adding controls

I'm trying to have panel displaying the result differently each time a user select items from pre-loaded combobox and dynamically created combobox.
Initially it will load a comboBox with item of ("HelloWorld"), each time when I do a SelectedIndexChanged with "HelloWorld", the panel will show 1.
However, problem lies on whenever I hit on add button and do SelectedIndexChanged with "HelloWorld" on the newly created button. It simply doesn't show 2 but instead when I hit on pre-loaded comboBox, it show 3.
Is it something to do with life-cycle events?
class form{
int index = 0;
private void formMain_Load(object sender, EventArgs e)
{
Button add = new Button();
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => { panel.Controls.Add(search()); });
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Text = index.ToString();
panel.Controls.Add(display);
});
return searchField;
}
}
I have tried many days and couldn't understand it ... Any helps would be appreciated. Thanks
int index { get; set; }
public Form2()
{
InitializeComponent();
index = 0;
Button add = new Button();
add.Text = "Add";
add.Location = new Point(search().Location.X + search().Width + 10, search().Location.Y);
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => {
panel.Controls.Add(search());
});
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.Name = "cmb " + index.ToString();
searchField.Location = new Point(10, (index + 1) * 20);
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Location = new Point(250, search().Location.Y-12);
panel.Controls.Add(display);
display.Text = index.ToString();
});
return searchField;
}

C# Updating Selected ComboBox Item Name from Textbox

I want to update comboBox selectedItem name by changing textbox name. Without losing combobox value, How can I achieve it?
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
nameItem.Text = "Item " + counter.ToString();
nameItem.Focus();
comboBox1.Items.Add(nameItem.Text);
comboBox1.SelectedItem = nameItem.Text;
counter++;
}
private void nameItem_TextChanged(object sender, EventArgs e)
{
????????
}
This one is simple and it's working, but it maybe a little bit long.
Here I got a combo box, textBox1 and button for adding value to combo box,
and textBox2 for editing selected item.
string[] items = new string[99];
int a = 0;
int i = 0;
private void button1_Click(object sender, EventArgs e)
{
items[i] = textBox1.Text;
i++;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++) {
if(items[n] != null) comboBox1.Items.Add(items[n]);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
a = comboBox1.SelectedIndex;
MessageBox.Show(a.ToString());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
items[a] = textBox2.Text;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++)
{
if (items[n] != null) comboBox1.Items.Add(items[n]);
}
}
How it works: we have an array for items and two integar variables. one for count of added items and other for selected Items index
Button 1 just addes new item, clears all items and update em again
when u edit text of textbox2, It will update items from 'items' array, and then update the combo box, ez
EDIT: Did not see winform tag - this will not work - will leave in case any ASP people come across.
public void TextBox1_OnTextChanged(object sender, EventArgs e)
{
ddl.DataSource = null;
ddl.DataBind();
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = (from ListItem b in ddl.Items
select b.Selected ? new ListItem(TextBox1.Text, b.Value) : b).ToList();
ddl.DataBind();
}
ddl is name of the dropdown box
Textbox1 is the name of the textbox.
This will change the name of the selected item. If you need more code let me know in comments.
Thank you for your time and kind answers.
I solved the problem as it looks below;
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
comboBox1.Items.Add("Item " + counter.ToString());
comboBox1.SelectedItem = "Item " + counter.ToString();
nameMacro.Text = "Item " + counter.ToString();
//comboBox1.SelectedItem = nameItem.Text;
//nameItem.Focus();
// Ad degistirme -> comboBox1.Items[comboBox1.FindStringExact("string value")] = "New Value";
counter++;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
comboBox1.Items[comboBox1.SelectedIndex] = nameItem.Text;
}
it's better to update the source then bind it again.
try this also
private void nameItem_TextChanged(object sender, EventArgs e)
{
string value = nameItem.Text;
var list = (List<KeyValuePair<String, String>>)comboBox1.DataSource;
list.Add(new KeyValuePair<string, string>(value,value));
comboBox1.DataSource = list;
comboBox1.DataBind();
}

Error with delegate instruction C#

I'm new on C# and i have many difulties, but now i'm still trying add an eventhandler to declared control like a variable, but if i use the delegate instruction i cant put this events because when i use the declaration:
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
Many error appears in a procedure that i caught in this forum, but i will put all procedure to you see.
private void Form1_Load(object sender, EventArgs e)
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = false;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
//Hide Column Header
listView1.HeaderStyle = ColumnHeaderStyle.None;
// Create three items and three sets of subitems for each item.
ListViewItem[] ItemsView = new ListViewItem[Quant_Items];
while (Item_Number <= (Quant_Items - 1))
{
ItemsView[Item_Number] = new ListViewItem(Item_name + Item_Number);
while (Sub_Item <= (Quant_SubItems - 1))
{
ItemsView[Item_Number].SubItems.Add("SubItem" + Sub_Item);
Sub_Item++;
}
Item_Number++;
}
Sub_Item = 0;
while (Sub_Item <= (Quant_SubItems - 1))
{
listView1.Columns.Add("Coluna" + Sub_Item);
Sub_Item++;
}
//Add the items to the ListView.
listView1.Items.AddRange(ItemsView);
//Autosize ListView
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(Quant_SubItems * 70, Quant_Items * 18));
// Add the ListView to the control collection.
this.Controls.Add(listView1);
listView1.MouseUp += new EventHandler(listView1_MouseUp);
}
//____________________________________________________________________
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
{
ListViewHitTestInfo i = listView1.HitTest(e.X, e.Y);
SelectedLSI = i.SubItem;
if (SelectedLSI == null)
return;
int border = 0;
switch (listView1.BorderStyle)
{
case BorderStyle.FixedSingle:
border = 1;
break;
case BorderStyle.Fixed3D:
border = 2;
break;
}
int CellWidth = SelectedLSI.Bounds.Width;
int CellHeight = SelectedLSI.Bounds.Height;
int CellLeft = border + listView1.Left + i.SubItem.Bounds.Left;
int CellTop = listView1.Top + i.SubItem.Bounds.Top;
// First Column
if (i.SubItem == i.Item.SubItems[0])
CellWidth = listView1.Columns[0].Width;
TxtEdit.Location = new Point(CellLeft, CellTop);
TxtEdit.Size = new Size(CellWidth, CellHeight);
TxtEdit.Visible = true;
TxtEdit.BringToFront();
TxtEdit.Text = i.SubItem.Text;
TxtEdit.Select();
TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
HideTextEditor();
}
private void HideTextEditor()
{
TxtEdit.Visible = false;
if (SelectedLSI != null)
SelectedLSI.Text = TxtEdit.Text;
SelectedLSI = null;
TxtEdit.Text = "";
}
}
}
Thanks for your help!
Just use this:
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
...
}
The delegate keyword doesn't belong in the method declaration, it's not valid in that context.
When you handle an event, you must supply a handler that matches the delegate type expected by this event. Loosley speaking, you need a method with the same signature expected by the handler.
For MouseUp, you need to supply a MouseEventHandler, see https://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventhandler(v=vs.110).aspx
You need to change the event subscription to
listView1.MouseUp += new MouseEventHandler(listView1_MouseUp);
Then change the signature of your handler to
private void listView1_MouseUp(object sender, MouseEventArgs e) { /*..*/}

How to get text from dynamically created textboxes in ASP.NET

I created dynamically some textboxes. They are created after click on one button(number of the textboxes depends on the user).
protected void Button1_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(TextBox2.Text);
Table tbl = new Table();
tbl.Width = Unit.Percentage(80);
TableRow tr;
TableCell tc;
TextBox txt;
CheckBox cbk;
DropDownList ddl;
Label lbl;
Button btn;
for (int j = 1; j <= i; j++)
{
tr = new TableRow();
tc = new TableCell();
tc.Width = Unit.Percentage(25);
lbl = new Label();
lbl.Text = "Pitanje:";
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
tc.Width = Unit.Percentage(25);
txt = new TextBox();
txt.ID = "txt_p_" + j;
tc.Controls.Add(txt);
tr.Cells.Add(tc);
tc.Width = Unit.Percentage(25);
lbl = new Label();
lbl.Text = "Odgovori:";
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
tc.Width = Unit.Percentage(25);
txt = new TextBox();
txt.ID = "txt_o_" + j;
tc.Controls.Add(txt);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);
}
Panel1.Controls.Add(tbl);
}
now I need to get the text that is typed into that textboxes. I tried with something that I found on the internet but can't get it to work.
protected void SpremiPitanja(object sender, EventArgs e)
{
int i = Convert.ToInt32(TextBox2.Text);
for (int j = 1; j <= i; j++)
{
***************************************
}
}
any kind of help is welcome. if you need more information I will give them
A variable declared in a function is only visible in a function. You need to store the TextBoxes in a variable, that exists even when the code in the function has "finished". For more information search for scopes.
Here is a small sample that stores TextBoxes in a List that is visible in your class.
Another option would be to use eventhandlers. It depends on your scenario, which solution would be suited better. If you store the TextBoxes in a List, you can easily perform clean up code (for instance remove EventHandlers if required). You can obviously combine Approach 1 and 2. In that case you would store the created TextBox in a List (or any other collection), but you would still use the sender in the eventhandler to get a reference to the sending TextBox.
public partial class Form1 : Form
{
List<TextBox> textBoxes = new List<TextBox>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Approach 1: create and add textbox to list
TextBox createdTextbox = new TextBox();
textBoxes.Add(createdTextbox);
}
private void button2_Click(object sender, EventArgs e)
{
//use the textboxes from the list
foreach(TextBox t in textBoxes)
{
//do something with t
}
}
private void button3_Click(object sender, EventArgs e)
{
//Approach 2: use eventhandlers and don't store textbox in a list
TextBox createdTextbox = new TextBox();
createdTextbox.TextChanged += createdTextbox_TextChanged;
listBox1.Items.Add(createdTextbox);
}
void createdTextbox_TextChanged(object sender, EventArgs e)
{
TextBox t = sender as TextBox;
if (t == null)
throw new ArgumentException("sender not of type TextBox", "sender");
//do something with t
}
}
You add textboxes the same way you do, this is my example (sorry it's vb.net):
Dim t As New TextBox With {.ID = "txt_123", .Text = "Vpiši"}
PlaceHolder1.Controls.Add(t)
t = New TextBox With {.ID = "txt_456", .Text = "Briši"}
PlaceHolder1.Controls.Add(t)
And then you iterate through controls in Placeholder (in my example):
Dim tItem As TextBox
Dim tValue As String = String.Empty
For Each c As Control In PlaceHolder1.Controls
If TypeOf c Is TextBox Then
tItem = c
tValue = tItem.Text.ToString
End If
Next
C# example added
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox t = new TextBox();
t.Text = "Vpiši";
t.ID = "txt_123";
PlaceHolder1.Controls.Add(t);
t = new TextBox();
t.Text = "Briši";
t.ID = "txt_456";
PlaceHolder1.Controls.Add(t);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox tItem;
String tValue;
foreach (Control c in PlaceHolder1.Controls)
{
if (c.GetType() == typeof(TextBox))
{
tItem = (TextBox)c;
tValue = tItem.Text;
}
}
}

Search in A ListBox

HI
I'm trying to put a textbox to search in a listBox.
I have a TextBox: SearchText with this code:
private void SearchText_TextChanged(object sender, EventArgs e)
{
int i = listBox3.FindString(SearchText.Text);
listBox3.SelectedIndex = i;
}
and a ListBox On the Load I have this code
List<string> str = GetListOfFiles(#"D:\\Music\\massive attack - collected");
listBox3.DataSource = str;
listBox3.DisplayMember = "str";
and on selectedIndexChanged :
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
player1.URL = listBox3.SelectedItem.ToString(); // HERE APPEAR THE ERROR "Object reference not set to an instance of an object."
// provaTxt.Text = listBox3.SelectedValue.ToString();
}
When I write down in the SeachText to find a songs I receive an error ("Object reference not set to an instance of an object.") in the line selectedIndexChanged of the ListBox.
Do you know one more way to find in a listBox as my case?
Thanks for your share.
Nice Regards
It sounds like the item wasn't found, so SelectedItem was null; try using:
player1.URL = Convert.ToString(listBox3.SelectedItem);
I believe this handles the null case (altenatively, test for null first).
I'd also be tempted to look in the underlying list:
List<string> items = (List<string>)listbox3.DataSource;
listbox3.SelectedIndex = items.FindIndex(s => s.StartsWith(searchFor));
For example:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
class MyForm : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
ListBox listbox;
TextBox textbox;
CheckBox multi;
public MyForm()
{
textbox = new TextBox { Dock = DockStyle.Top };
List<string> strings = new List<string> { "abc", "abd", "abed", "ab" };
listbox = new ListBox { Dock = DockStyle.Fill, DataSource = strings };
textbox.KeyDown += textbox_KeyDown;
Controls.Add(listbox);
Controls.Add(textbox);
listbox.SelectedIndexChanged += listbox_SelectedIndexChanged;
listbox.SelectionMode = SelectionMode.MultiExtended;
multi = new CheckBox { Text = "select multiple", Dock = DockStyle.Bottom };
Controls.Add(multi);
}
void listbox_SelectedIndexChanged(object sender, EventArgs e)
{
Text = Convert.ToString(listbox.SelectedItem);
}
void textbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
string searchFor = textbox.Text;
List<string> strings = (List<string>)listbox.DataSource;
if (multi.Checked)
{
for (int i = 0; i < strings.Count; i++)
{
listbox.SetSelected(i, strings[i].Contains(searchFor));
}
}
else
{
listbox.ClearSelected();
listbox.SelectedIndex = strings.FindIndex(
s => s.Contains(searchFor));
}
}
}
}

Categories