how can i search Controls in flow Layout panel? - c#

In my flow layout panel it load pic and name in user control.
I try this, which is working fine
foreach (DataRow row in dt.Rows)
{
byte[] data = (byte[])row["Image"];
pic = new PictureBox();
pic.Width = 150;
pic.Height = 150;
pic.BackgroundImageLayout = ImageLayout.Stretch;
pic.BorderStyle = BorderStyle.FixedSingle;
string type = row.Table.Columns.Contains("liquidPriceId") ? "liquidPrice" : "itemMaster";
string tag = row.Table.Columns.Contains("liquidPriceId") ? row["liquidPriceId"].ToString() : row["itemMasterId"].ToString();
MemoryStream ms = new MemoryStream(data);
pic.BackgroundImage = new Bitmap(ms);
Label name = new Label();
name.Text = row["Name"].ToString();
name.BackColor = Color.FromArgb(45, 66, 91);
pic.Controls.Add(name);
flp.Controls.Add(pic);
}
THEN in my search text change I try this, my problem is I don't know how to get the name for filtering
foreach (Control c in flowLayoutPanel3.Controls)
how to get inside c of my pic and name values ?
private void txtSearchBox_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearchBox.Text;
try
{
if (txtSearchBox.Text.Length > 0)
{
string compareTo = String.Concat("*", txtSearchBox.Text.ToLower(), "*");
foreach (Control c in flowLayoutPanel3.Controls)
{
c.Visible =(c.Name.ToLower() == compareTo); // c.Name is empty how can i get name ?
}
}
else
{
foreach (Control c in flowLayoutPanel3.Controls)
{
c.Visible = true;
}
}
}
}

When you create the PictureBox control, I would make the Name property the same as the Text property of the Label:
name.Text = row["Name"].ToString();
pic.Name = name.Text;
But, you are adding * to the beginning and end of your search string. So do you want a match if the search value is contained anywhere within the Name property?
If yes, then you could just use String.Contains():
string compareTo = txtSearchBox.Text.Trim().ToLower();
foreach (Control c in flowLayoutPanel3.Controls)
{
c.Visible = c.Name.ToLower().Contains(compareTo);
}

It's not clear from the code and text provided, but it seems that what you might need is to set the Name property of the control(s) you create in the first code snippet. Something like this:
//...
pic = new PictureBox();
pic.Name = "My Picture";
// ...
I would also change the comparison from this:
c.Visible =(c.Name.ToLower() == compareTo);
to this:
c.Visible = c.Name.StartsWith(compareTo, StringComparison.CurrentCultureIgnoreCase);

Related

WinForms - Dynamically create textbox based on ComboBox selection

I am trying to create a TextBox based on the selection on ComboBox dynamically based on the following steps:
First step (Select a source from ComboBox):
Second step (Textbox should appear based on ComboBox.SelectedValue):
Last step (A new ComboBox should appear below):
I have created a createTextBox function using the following code:
public void createTextBox(int numPassenger)
{
TextBox[] passengerBoxes = new TextBox[numPassenger];
for (int u = 0; u < passengerBoxes.Count(); u++)
{
passengerBoxes[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in passengerBoxes)
{
string name = "passenger" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(244, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
Is there a way that I can modify my current function to adapt to the mentioned steps? Additionally, how can I find the dynamically created TextBox?
You can try the following code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
createTextBox(sender as ComboBox);
}
private void createTextBox(ComboBox cmb)
{
TextBox passengerBoxes = new TextBox();
string name = cmb.Text;
if (Controls.Find(name, true).Length == 0)
{
passengerBoxes.Name = name;
passengerBoxes.Text = name;
int textBoxCount = GetTextBoxCount();
passengerBoxes.Location = new Point(244, 32 + (textBoxCount * 28));
passengerBoxes.Visible = true;
this.Controls.Add(passengerBoxes);
if (cmb.Items.Count != 1)//last item remaining then we should not create new combo box
{
ComboBox newCombo = new ComboBox
{
Location = new Point(cmb.Location.X, 32 + ((textBoxCount + 1) * 28))
};
foreach (string str in cmb.Items)
if (cmb.Text != str)
newCombo.Items.Add(str);
newCombo.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
this.Controls.Add(newCombo);
}
}
else
MessageBox.Show("Textbox Already for the selected source " + name);
}
private int GetTextBoxCount()
{
int i = 0;
foreach (Control ctl in this.Controls)
{
if (ctl is TextBox) i++;
}
return i;
}

how to save data from dynamic textbox?

this code creates a textbox dynamically based on the total number of items in a listview. my problem is how can i access these textboxes so i can save the contents of the textbox to my database?
int f = 24;
int j = 25;
for (int gg = 0; gg < listView1.Items.Count;gg++ )
{
j = f + j;
TextBox txtb = new TextBox();
txtb.Name = "tboxl1"+gg;
txtb.Location = new Point(330,j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily,12);
groupBox2.Controls.Add(txtb);
}
I'd be more inclined to write you code like this:
var f = 24;
var j = 25;
var textBoxes =
Enumerable
.Range(0, listView1.Items.Count)
.Select(gg =>
{
j = f + j;
var txtb = new TextBox();
txtb.Name = String.Format("tboxl1{0}", gg);
txtb.Location = new Point(330, j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily, 12);
return txtb;
})
.ToList();
textBoxes.ForEach(txtb => groupBox2.Controls.Add(txtb));
Now you have a variable textBoxes that saves references to the new text boxes. You can use that to get the values from the text boxes to save them to your database.
If you want all TextBox controls then:
foreach (Control control in groupBox2.Controls)
{
if (control is TextBox)
{
string value = (control as TextBox).Text;
// Save your value here...
}
}
But if you want a specific TextBox, you can get it by its name like this:
Control control = groupBox1.Controls.Find("textBox1", false).FirstOrDefault(); // returns null if no control with this name exists
TextBox textBoxControl = control as TextBox; // if you want TextBox control
string value = control.Text;
// Now you can save your value anywhere
You can get the reference to text box as follows,
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}

Get text from dynamically created WinForms textbox

I'm making a windowsform with dynamically created textboxes as u see in the method.
public void createPassengerBoxes(int numPassenger)
{
TextBox[] passengerBoxes = new TextBox[numPassenger];
for (int u = 0; u < passengerBoxes.Count(); u++)
{
passengerBoxes[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in passengerBoxes)
{
string name = "passenger" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(244, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
}
How do I access the text from the boxes?
While I'm not sure at what point, or based on what action, you'd like to fetch the data, here's very generic method:
private String[] GetTextBoxStrings()
{
List<String> list = new List<String>();
foreach (Control c in this.Controls)
{
if (c is TextBox)
list.Add(((TextBox)c).Text);
}
return list.ToArray();
}
Move your textbox declaration outside of the function. This makes it accessible from other functions within the class:
class MyFormsClass
{
// declare textboxes at class level
TextBox[] passengerBoxes;
public void createPassengerBoxes(int numPassenger)
{
passengerBoxes = new TextBox[numPassenger];
...
}
public void OnButtonClick(...)
{
if (passengernBoxes != null)
{
foreach (TextBox txt in passengerBoxes)
{
// do something with textboxes
}
}
}
...
}
You could also use Lambda:
var strings = Controls.OfType<TextBox>()
.Select(c => c.Text)
.ToList();
this only work if ou have no nested controls - e.g. a pannel or a group that holds some textBoxes

DataGridViewImageColumn don't display the value - why?

I want to display some images in my dataGridView, so I created DataGridViewImageColumn with default image (Properties.Resources.test), added it to dataGridView and tried to insert some values to cells. Unfortunately it didn't change the display. What Am I doing wrong?
var q = from a in _dc.GetTable<Map>() select a;
View.dataGridView1.DataSource = q;
View.dataGridView1.Columns[3].Visible = false;
var imageColumn = new DataGridViewImageColumn
{
Image = Properties.Resources.test,
ImageLayout = DataGridViewImageCellLayout.Stretch,
Name = "Map",
HeaderText = #"map"
};
View.dataGridView1.Columns.Add(imageColumn);
var i = 0;
foreach (var map in q)
{
View.dataGridView1.Rows[i].Cells[8].Value = ByteArrayToImage(map.map1.ToArray());
i++;
}
As explained in the question in the comment you need to use the CellFormatting event like so:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "StatusImage")
{
// Your code would go here - below is just the code I used to test
e.Value = Image.FromFile(#"C:\Pictures\TestImage.jpg");
}
}
So set e.Value rather than cell.Value and assign the image.
you can do like this...
for(int i = 0; i < dataGridView1.Columns.Count; i ++)
if(dataGridView1.Columns[i] is DataGridViewImageColumn) {
((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}

Hiddenfield WebControl

foreach (var item in AnketSoru)
{
r = new HtmlTableRow();
c = new HtmlTableCell();
c.InnerHtml = item.new_question_text.ToString();
r.Cells.Add(c);
switch (item.new_question_type.ToString())
{
case "2": //FreeText
c = new HtmlTableCell();
TxtFreeText = new TextBox();
TxtFreeText.ID = "Txt_" + item.new_survey_questionid.ToString();
TxtFreeText.TextMode = TextBoxMode.MultiLine;
TxtFreeText.Width = 300;
TxtFreeText.Height = 50;
TxtFreeText.EnableViewState = true;
c.Controls.Add(TxtFreeText);
HiddenField txthfield = new HiddenField();
txthfield.Value = item.new_name.ToString();
c.Controls.Add(txthfield);
and
foreach (Control c in plc.Controls)
{
System.Web.UI.HtmlControls.HtmlTable Survey_Inner = (System.Web.UI.HtmlControls.HtmlTable)c.FindControl("Survey_Inner");
foreach (System.Web.UI.HtmlControls.HtmlTableRow r in Survey_Inner.Rows)
{
foreach (Control ctr in r.Cells)
{
foreach (Control ct in ctr.Controls)
{
if (ct.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
string freeTxtQues = ?? ;
string TextCevap = ((System.Web.UI.WebControls.TextBox)ct).Text;
string deger = ct.ID.ToString();
Guid QuestionId = new Guid(deger.Substring(4));
SaveAnswers(this._PortalUserHelper.UserProxy.ContactId, EgitimKatilimcisi, QuestionId, TextCevap, freeTxtQues);
}
i tryed
string freeTxtQues = ((System.Web.UI.WebControls.HiddenField)ct).Value;
but returns me error. "InvalidCastException was unhandled by user code."
'System.Web.UI.WebControls.TextBox' türündeki nesne 'System.Web.UI.WebControls.HiddenField' türüne atılamadı.
I'm trying to reach hiddenfields value's and set them to the freeTxtQues value but couldn't able to do it for now. Any help for how can i do that?
Hard to understand your question/problem but I will throw something...
When you create dynamic controls you need to create them on Init event so when ViewState is applied he finds the controls and sets their values. If you are not creating the controls in Init but later, you will found out that the control doesn't have the supposed value!

Categories