Hiddenfield WebControl - c#

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!

Related

how can i search Controls in flow Layout panel?

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);

C# Error when searching for control in UpdatePanel

I have a little problem. First of all, some info:
- On my page, I have an UpdatePanel with a button inside it.
- When you click this button, I generate a new row with dropdown lists. Each time I have to generate a table from scratch, because it resets after the click, so I update [ViewState] value and generate as many rows as clicks.
- Outside the panel, I have another button. After clicking this button, I want to collect data from drop-down lists. To do it, I have to get to these controls.
I tried to use function FindControl(), but I guess I can't - as far as I know, it does not perform a deep search. This means I have to pass as a parameter the exact container with this control. Because control is inside the table, I should get to the <td> value and I can't do that (<td> does not have ID - yes, I can add it but <td> is also dynamically created. That means I would need to get first to <td>, then to my control (guess what - <tr> is also created dynamically).
Because I can't use FindControl function, I use FindRecursiveControl function (code below) The problem is, that this function neither finds anything. Any suggestions about what might be the reason? I added this whole info in case that the reason is for example usage of UpdatePanel and page life cycle.
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID)
{
return rootControl;
}
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null)
{
return controlToReturn;
}
}
return null;
}
My usage of this function:
string control_id = "parametr" + i;
DropDownList dropdown = (DropDownList)FindControlRecursive(UpdatePanel1, control_id);
Script generating table in UpdatePanel after button click
protected void generuj_tabele(int il_klik)
{
il_par.Text = "Ilość parametrów: " + il_klik.ToString();
TableRow table_head = new TableRow();
table_head.Attributes.Add("class", "w3-green");
Table1.Rows.Add(table_head);
for (int j = 0; j < 5; j++)
{
TableCell cell = new TableCell();
table_head.Cells.Add(cell);
}
Table1.Rows[0].Cells[0].Text = "Parametr";
Table1.Rows[0].Cells[1].Text = "Wartość początkowa";
Table1.Rows[0].Cells[2].Text = "Inkrementacja?";
Table1.Rows[0].Cells[3].Text = "Zwiększ o:";
Table1.Rows[0].Cells[4].Text = "Zwiększ co:";
RootObject obj = (RootObject)Session["get_offer"];
for (int i = 0; i < il_klik; i++)
{
parametr = new DropDownList();
wartosc = new TextBox();
inkrementacja = new CheckBox();
inkrementacja_numer = new TextBox();
skok = new TextBox();
//inkrementacja_numer.Enabled = false;
// skok.Enabled = false;
inkrementacja_numer.Attributes.Add("Type", "number");
skok.Attributes.Add("Type", "number");
//inkrementacja.CheckedChanged += new EventHandler((s, eventarg) => checkbox_change(s, eventarg, i));
//inkrementacja.AutoPostBack = true;
//parametr.AutoPostBack = true;
TableRow row = new TableRow();
Table1.Rows.Add(row);
parametr.EnableViewState = true;
wartosc.EnableViewState = true;
inkrementacja.EnableViewState = true;
inkrementacja_numer.EnableViewState = true;
skok.EnableViewState = true;
for (int j = 0; j < 5; j++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
}
Table1.Rows[i + 1].Cells[0].Controls.Add(parametr);
Table1.Rows[i + 1].Cells[1].Controls.Add(wartosc);
Table1.Rows[i + 1].Cells[2].Controls.Add(inkrementacja);
Table1.Rows[i + 1].Cells[3].Controls.Add(inkrementacja_numer);
Table1.Rows[i + 1].Cells[4].Controls.Add(skok);
if (i == il_klik - 1)
{
wystaw_liste(obj);
Price pr = obj.sellingMode.price;
parametr.Items.Add(pr.amount.ToString());
List<Parameter> par = obj.parameters;
foreach (Parameter p in par)
{
List<string> val = p.values;
if (val.Count() > 0)
{
foreach (string v in val)
{
parametr.Items.Add(v);
}
}
}
foreach (string p in parametry_list)
{
parametr.Items.Add(p);
}
parametry_list.Clear();
}
parametry.Add(parametr);
wartosci.Add(wartosc);
inkrementacje.Add(inkrementacja);
inkrementacje_numery.Add(inkrementacja_numer);
skoki.Add(skok);
if (i == il_klik - 1)
{
Session["v_parametr"] = parametry;
Session["v_wartosc"] = wartosci;
Session["v_inkrementacja"] = inkrementacje;
Session["v_ink_nr"] = inkrementacje_numery;
Session["v_skok"] = skoki;
}
parametr.ID = "parametr" + i;
wartosc.ID = "wartosc" + i;
inkrementacja.ID = "inkrementacja" + i;
inkrementacja_numer.ID = "inkrementacja_numer" + i;
skok.ID = "skok" + i;
}
}
When I try to check parameters of DropDownList (e.g. SelectedValue) I get error "Object reference not set to an instance of an object"

Textbox SpellCheck.IsEnabled - How to count

My Textbox needs to work out the number of spelling errors occur in a textbox.
My research has shown me how to get the spelling errors to work, using
<TextBox Text="{Binding Content}" SpellCheck.IsEnabled="True" Language="en-GB" />
I was slightly annoyed that I can't have IsReadOnly set to true but, I guess I have to live with it.
What I can't find out is how to know how many spelling issues/errors are in the Textbox. All I can find is http://msdn.microsoft.com/en-us/library/system.windows.controls.spellcheck%28v=vs.110%29.aspx which doesn't say it does but I'm not losing hope!
I tried to add
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf and tre";
var split = tx.Text.Split(' ');
var errors = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.Text = s;
SpellingError e = tempTb.GetSpellingError(0); // always null
var a = tempTb.GetSpellingErrorLength(0);
var b = tempTb.GetSpellingError(0);
var c = tempTb.GetSpellingErrorStart(0);
if ( tempTb.GetSpellingErrorLength(0) >= 0)
errors++;
}
If I update the code from
SpellingError e = tempTb.GetSpellingError(0); // always null
to
SpellingError e = tx.GetSpellingError(0); // not null
Then it provides suggestions which then informs me it's wrong (and I can perform a count).
To get around the issue I'm having to do
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf many tre further more i sense taht nothing is what is";
var split = tx.Text.Split(' ');
var errors = 0;
var start = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.Text = s;
SpellingError f = tx.GetSpellingError(start);
start += s.Length + 1;
if (f!=null)
errors++;
}
Why does it not work for tempTb?
It appears from my debugging that #EdSF is correct and SpellCheck.IsEnabled must be set for the temporary TextBox
Code used to reproduce this:
void initTest()
{
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf and tre";
var split = tx.Text.Split(' ');
var errors = 0;
foreach (var s in split)
{
var tempTb = new TextBox();
tempTb.SpellCheck.IsEnabled = true; // Added this line
tempTb.Text = s;
SpellingError e = tempTb.GetSpellingError(0); // no longer always null
var a = tempTb.GetSpellingErrorLength(0);
var b = tempTb.GetSpellingError(0);
var c = tempTb.GetSpellingErrorStart(0);
//if (tempTb.GetSpellingErrorLength(0) >= 0) //doesn't appear to be correct
if (e != null)
{
errors++;
}
}
}
I found it after I posted
There is
GetSpellingErrorStart()
GetSpellingError()
GetSpellingErrorLength()
SpellingError e = tempTb.GetSpellingError(0);
EG
TextBox tx = new TextBox();
tx.SpellCheck.IsEnabled = true;
tx.Text = "saf";
var reslt = tx.GetSpellingErrorStart(0);

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;
}

How to access multiple buttons or textbox or any control?

I want to access multiple textbox name textbox1,textbox2,textbox3, etc.. by loop not by individual name. For that reason I created one function which create this var names.
public string[] nameCre(string cntrlName, int size)
{
string[] t = new string[size];
for (int i = 0; i < size; i++)
{
t[i] = cntrlName.ToString() + (i + 1);
}
return t;
}
for nameCre("Textbox",5); So this,function successfully returning me TextBox1, TextBox2 ... TextBox5.
But when I am trying to convert this string to TextBox control by
string[] t = new string[50];
t= nameCre("TextBox",5);
foreach (string s in t)
{
((TextBox) s).Text = "";
}
it giving me error :
Cannot convert type 'string' to 'System.Windows.Forms.TextBox'....
How can I accomplish this job?
var t = nameCre("TextBox",5);
foreach (var s in t)
{
var textBox = new TextBox {Name = s, Text = ""};
}
string[] t= new string[50];
t= nameCre("TextBox",5);
foreach (string s in t){
TextBox tb = (TextBox)this.Controls.FindControl(s);
tb.Text = "";
}
if you have many text boxes
foreach (Control c in this.Controls)
{
if (c.GetType().ToString() == "System.Windows.Form.Textbox")
{
c.Text = "";
}
}
Perhaps you need this -
string[] t = new string[50];
t = nameCre("TextBox", 5);
foreach (string s in t)
{
if (!string.IsNullOrEmpty(s))
{
Control ctrl = this.Controls.Find(s, true).FirstOrDefault();
if (ctrl != null && ctrl is TextBox)
{
TextBox tb = ctrl as TextBox;
tb.Text = "";
}
}
}
This post is quite old, anyway I think I can give you (or anyone else with a problem like that) an answer:
I think using an Array (or List) of TextBoxs would be the best solution for doing that:
// using an Array:
TextBox[] textBox = new TextBox[5];
textBox[0] = new TextBox() { Location = new Point(), /* etc */};
// or
textBox[0] = TextBox0; // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Length; i++)
{
textBox[i].Text = "";
}
// using a List: (you need to reference System.Collections.Generic)
List<TextBox> textBox = new List<TextBox>();
textBox.Add(new TextBox() { Name = "", /* etc */});
// or
textBox.Add(TextBox0); // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Count; i++)
{
textBox[i].Text = "";
}
I hope this helps :)

Categories