how to find correct textbox from name? - c#

I have 30 TextBox in my form. And i want to select correct one and write value there.
My textboxes names are :
tb_0_X, tb_0_Y,tb_1_X, tb_1_Y,tb_2_X, tb_2_Y, .... goes like this..
And i can create my textbox name :
string tbName = pointLoc.ToString();
string tbFirst = "tb_";
string tbLastX = "_X";
string tbLastY = "_Y";
string tbX = tbFirst + tbName + tbLastX;
string tbY = tbFirst + tbName + tbLastY;
Instead of writing all textbox such as :
tb_0_X.text = "";
tb_0_Y.text = "";
...
..
.
.
..
I want to write tbX or tbY but it is not possible to write ..
tbX.text = "someString";
how can i handle this issue ,?
EDIT :
To be more clearly ..
string tbName comes from radioButton. So i need to find which textbox i should change from tbX or tbY..
therefore i need to do something like tbX.text = "someString";

string tbX = "textBox1"; // or whatever you want to call it
TextBox tb = this.Controls.Find(tbX, false).FirstOrDefault() as TextBox;
if (tb != null)
{
tb.Text = "Test";
}
The this keyword obviously represents the form the textbox is on.

Related

Replace '\n' in multiple textbox at once

I have a window form application, inside this application, there have several textbox and want to replace the breakline and send out as email in one click. Since i have multiple textbox, instead of writing like this:
string text = textBox1.Text;
text = text.Replace("\n", "<br/>");
string text2 = textBox2.Text;
text2 = text2.Replace("\n", "<br/>");
...
string textBody ="<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text + "</td></tr>" +"<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>" + ...
is there any ways to replace the line in these textbox in one time?
I try to put in a loop:
for (int i = 1; i < 20; i++)
{TextBox txtbox = (TextBox)this.Controls.Find("textBox" + i, true)[0]; }
I stuck at here. Any suggestion?
Your Form is a Control, which has a property Controls This property "Gets the collection of controls contained within the control".
You can use Enumerable.OfType to filter this so you get only the TextBoxes.
Is there any ways to replace the line in these textbox in one time?
You'll need a foreach to replace the text:
var textBoxesToUpdate = this.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxesToUpdate)
{
string proposedText = textBox.Text.Replace("\n", "<br/>");
textBox.Text = proposedText;
}
I also see this in your question
string textBody = "<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text1 + "</td></tr>"
+ "<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>"
+ ...
I don't know what you want with this. Consider to edit the question and change this.

Get values from one textbox and put them in another textboxes

I have values from a textbox :
"r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C"
and I want to make each value show in another textboxes like this:
textbox 1:
a: "00.00"
textbox 2:
b: "0000521135"
textbox 3:
c: "0000000.000"
textbox 4:
d: "025.1"
I can do this in arduino using parseInt(),
I wonder how to do this in c#, any help?
you can use a string.split() function to extract value from first textbox.
string baseStr = "r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C";
List<string> colStr= test.Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
and then remove alphabet using regular expression
using System.Text.RegularExpressions;
...
Textbox1.Text = Regex.Replace(colStr[1], "[A-Za-z]", "");
Textbox2.Text = Regex.Replace(colStr[2], "[A-Za-z]", ""));
...
This will give you the idea how to put the data in the textboxes. I have done it for a string variable.
string s1 = "r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C";
string[] spliteds1 = s1.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string txt1 = "";
foreach(string elem in spliteds1)
{
if(Regex.Replace(elem, "[^0-9.]", "") != "")
{
txt1 = txt1 + Regex.Replace(elem, "[^0-9.]", "") + ",";
}
}
This code will put the in txt1 with comma seperator. You can run your loop for textboxes.
Hope this helps

Save text from multiple objects depending on bool value

I don't know any other way to explain this apart from providing an image of what I'm doing.
Basically, the Save Cheats button creates a text file that has the information from the 3 textboxes (cheattbox, cheatobox, cheatbbox) numbered respectably. There are 20 total boxes, and to save space only those with data should be saved. Let's say someone wants to save the information from boxes 4, 7, 8 and 13, with those checkboxes checked, I want the text file to only contain information from those given boxes.
Here is the code I have thus far.
public string savemagic(int i)
{
CheckBox tickbox = this.Controls.Find("ccheatcbox" + i.ToString(), true).FirstOrDefault() as CheckBox;
TextBox namebox = this.Controls.Find("ccheatname" + i.ToString(), true).FirstOrDefault() as TextBox;
ComboBox byteselect = this.Controls.Find("ccheatbytebox" + i.ToString(), true).FirstOrDefault() as ComboBox;
TextBox offsetbox = this.Controls.Find("ccheatofsetbox" + i.ToString(), true).FirstOrDefault() as TextBox;
TextBox bytebox = this.Controls.Find("ccheatbytes" + i.ToString(), true).FirstOrDefault() as TextBox;
fu[i] = string.Format("{0} - {1} - {2}\n",namebox.Text, offsetbox.Text, bytebox.Text);
return fu[i];
}
int checkint;
string[] fu = new string[9999];
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog _SD = new SaveFileDialog();
_SD.Filter = "Text File (*.txt)|*.txt|Show All Files (*.*)|*.*";
_SD.FileName = "Untitled";
_SD.Title = "Save As";
if (_SD.ShowDialog() == DialogResult.OK)
{
foreach(var controls in ccheattab.Controls)
{
if (controls is CheckBox && ((CheckBox)controls).Checked)
{
string tmp = ((CheckBox)controls).Name.Replace("ccheatcbox", "");
checkint = Convert.ToInt32(tmp);
File.WriteAllText(_SD.FileName, savemagic(checkint));
}
}
}
}
You could try just having the checkbox see if it's ticked or not like so
public string savemagic(int i)
{
CheckBox tickbox = this.Controls.Find("ccheatcbox" + i.ToString(), true).FirstOrDefault() as CheckBox;
if (tickbox.Checked) {
TextBox namebox = this.Controls.Find("ccheatname" + i.ToString(), true).FirstOrDefault() as TextBox;
ComboBox byteselect = this.Controls.Find("ccheatbytebox" + i.ToString(), true).FirstOrDefault() as ComboBox;
TextBox offsetbox = this.Controls.Find("ccheatofsetbox" + i.ToString(), true).FirstOrDefault() as TextBox;
TextBox bytebox = this.Controls.Find("ccheatbytes" + i.ToString(), true).FirstOrDefault() as TextBox;
string Cheats= string.Format("{0} - {1} - {2}\n",namebox.Text, offsetbox.Text, bytebox.Text);
return Cheats;
}
return "";
}
https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.checked%28v=vs.110%29.aspx
Also, for actually writing to the file, think about using a StreamWriter instead of using File.WriteAllText unless you're going to use a StringBuilder to put these strings together.
This is what happens when you call File.WriteAllText:
Creates a new file, write the contents to the file, and then closes
the file. If the target file already exists, it is overwritten.
For a start it would help you a lot if you abstract your model and have a slight separation form UI, it's just going to confuse you when you are dealing with your business logic.
class CheatObject {
public string Name { get; set; }
public string SelectType { get; set; } // or use enum for this
public string OffsetStr{ get; set; }
public string ByteStr { get; set; }
public ExportToFile() {
// logic to export a CheatModel
}
}
...
Once you have this, it will be much simpler. Your question could be only, what is the best way to get which rows are checked.
Then: foreach (all checked boxes) cheatModelFromRow.ExportToFile();

How to create RequiredFieldValidator at the same time as textboxes that I generated in C#?

In C# server side codes, I already successful created a textboxes based on user select how many they want to fill it out. Now I want to created a RequiredFieldValidators to validate these textboxes I generated to ensure that the users doesn't leave the textboxes blank. I don't know how that work but I am sure it need to put inside foreach loop to create validators at the same time as textboxes. Please help
C# codes,
int num = 1;
foreach(PSObject psObject in output)
{
HtmlGenericControl div = new HtmlGenericControl("div");
Label ipLabel = new Label();
ipLabel.Text = psObject + "<br/>";
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(ipLabel);
div.Controls.Add(t);
phDynamicTextBox.Controls.Add(div);
tbids.Add(t.ID);
num++;
}
Session["tbids"] = tbids;
HTML codes,
<div id="div1" runat="server">
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
</div>
You just need to create RequiredFieldValidator similar to Label and TextBox control.
Only difference is you need to assign TextBox's ID to ControlToValidate.
...
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(ipLabel);
div.Controls.Add(t);
var rfv = new RequiredFieldValidator();
rfv.ID = "RequiredFieldValidator" + num;
rfv.ControlToValidate = t.ID;
rfv.ErrorMessage = num + " is required.";
div.Controls.Add(rfv);
phDynamicTextBox.Controls.Add(div);
...
#Win Answer is correct, here is a fancy way to do it:
var textBoxValidator = new RequiredFieldValidator
{
ID = "textBoxValidator" + num,
ControlToValidate = t.ID,
Display = ValidatorDisplay.Dynamic,
ErrorMessage = String.Format("The TextBox field #{0} Cannot be blank", num),
ForeColor = Color.Red
};
div.Controls.Add(textBoxValidator);

Insert and remove Template textbox column in grid view

class TextColumn : ITemplate
{
private string controlId;
private string cssClass;
public TextColumn(string id, string cssClass = "inputFromTo")
{
controlId = id;
this.cssClass = cssClass;
}
public void InstantiateIn(Control container)
{
TextBox txt = new TextBox();
txt.ID = controlId;
txt.CssClass = cssClass;
container.Visible = true;
container.Controls.Add(txt);
}
}
/************************************ Add column code snippet ****************************/
TemplateField dentry = new TemplateField();
TemplateField dexit = new TemplateField();
TemplateField dslack = new TemplateField();
dentry.ItemTemplate = new TextColumn("txtHH" + nameCount + "DEntry");
dexit.ItemTemplate = new TextColumn("txtHH" + nameCount + "DExit");
dslack.ItemTemplate = new TextColumn("txtHH" + nameCount + "DSlack");
gvOfcBlowingReport.Columns.Insert(startPoint, dentry);
gvOfcBlowingReport.Columns.Insert(startPoint + 1, dexit);
gvOfcBlowingReport.Columns.Insert(startPoint + 2, dslack);
/********************************* Remove column code snippet ************************/
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 1);
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 2);
gvOfcBlowingReport.Columns.RemoveAt(startPoint - 3);
// after executing this code all the columns vanish.
Anyone know how to remove this text box template column?
In the above code I am adding templated field textbox and later on removing the same on button click but due to some reason all the templated field are getting affected and returning null when i am using FindControl in grid. In display also grid is displayed as empty.
Some other people are also facing the same problem over http://forums.asp.net/t/1162011.aspx but so far no valuable solution.

Categories

Resources