How to use input from dynamic generated textboxes in windows forms? - windows-forms-designer

I am working on a windows forms project. Theres a button which generates new textboxes.
TextBox txtbox = new TextBox();
this.positionY += 40;
txtbox.Location = new System.Drawing.Point(this.positionX, this.positionY);
this.Controls.Add(txtbox);
How can I get the input from these generated textboxes?
Can someone help me?
Best regards
JuRi-2020

You must create an array of text boxes and then access them as array items.
I hope the following code helps.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int positionX = 10;
int positionY = 0;
TextBox[] txtboxes = new TextBox[3];
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < txtboxes.Length; i++)
{
this.positionY += 40;
txtboxes[i] = new TextBox();
txtboxes[i].Location = new System.Drawing.Point(this.positionX, this.positionY);
this.Controls.Add(txtboxes[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
string str = "";
for(int i=0; i<txtboxes.Length;i++)
str += txtboxes[i].Text + "\n";
MessageBox.Show(str);
}
}
}

Related

how to get value from dynamically created textbox in asp.net

hi i'm Cannot get value dynamically created textbox and save into database. plz help
his is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error
protected void btnAtt_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
for (int i = 0; i < query.Count(); i++)
{
Label lblatt = new Label();
lblatt.ID = query[i].AttributeName;
lblatt.Text = query[i].AttributeName + " : ";
lblatt.CssClass = "control-label";
TextBox txtatt = new TextBox();
txtatt.ID = "txtatt"+i;
txtatt.Attributes.Add("runat", "server");
txtatt.Text = String.Empty;
txtatt.CssClass = "form-control input-sm";
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(lblatt);
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(txtatt);
HtmlTextWriterTag.Br.ToString();
}
}
protected void lbtnSave_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
int LastId = database.tbl_Products.Max(p => p.ProductId);
for (int i = 0; i < query.Count(); i++)
{
database.tbl_ProductValue.Add(new Models.tbl_ProductValue()
{
ProductId_FK = LastId,
AttributeID_FK = query[i].Attribute_Id,
ProductValue = ??,
});
database.SaveChanges();
}
}
plz help me for how to get textbox?
I haven't worked with WebForms in a while but you can access the controls by their IDs like this:
ProductValue = ((TextBox)FindControl("txtatt" + i)).Text;

Can't dynamically add controlvalidation to textbox

After several searches on the Internet finally decided to drop a question.
At runtime I want the following to happen.
If you push a button a textbox will be added to the controls and a custom validator must be attached to the textbox and fire.
It does not fire. Why?
Here is my code
Thank you for looking into this.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
CustomValidator rv2 = new CustomValidator();
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rv2.ID = "rev2";
rv2.ErrorMessage = "Not numeric input";
rv2.ClientValidationFunction = "";
rv2.ServerValidate += new ServerValidateEventHandler(GetalValidator);
Controls.Add(rv2);
}
}
protected void ButtonClick(object sender, EventArgs args)
{
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
this.Controls.Add(tb1);`enter code here`
rv2.EnableClientScript = false;
rv2.ControlToValidate = "tb2";
}
private bool IsNumber(string someText)
{
int number;
bool result = Int32.TryParse(someText, out number);
return result;
}
protected void GetalValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = IsNumber(args.Value);
}
}
here is part of code thorugh which you can add validation on your dynamically created control.
TextBox tb1 = new TextBox();
tb1.ID = "tb2";
tb1.Visible = true;
tb1.Width = 30;
RequiredFieldValidator regfv = new RequiredFieldValidator();
regfv.ID = "regfv";
regfv.ControlToValidate = tb1.ID;
regfv.ErrorMessage = "My Error";
this.Controls.Add(tb1);
this.Controls.Add(regfv);

asp.net gridview outside button to save

I have gridview built dynamically at run-time bind to datatable, and button to save gridview data placed outside gridview
1- Create GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateGrid();
}
}
void CreateGrid()
{
int nTransID = Convert.ToInt32(Session["trans_id"]);
//
string strSQL = #"EXEC [dbo].[sp_GetTransaction] " + nTransID;
DataTable dtData = clsGlobal.GetDataTable(strSQL);
//
if (ViewState["dtTransDetail"] == null) ViewState.Add("dtTransDetail", dtData);
else ViewState["dtTransDetail"] = dtData;
//
foreach (DataColumn dc in dtData.Columns)
{
if (dc.ColumnName.Contains("!;"))
{
TemplateField tField = new TemplateField();
tField.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, dc.ColumnName);
//\\ --- template contain textbox
tField.HeaderText = dc.ColumnName;
GridView1.Columns.Add(tField);
}
}
}
This is my template class:
public class AddTemplateToGridView : ITemplate
{
ListItemType _type;
string _colName;
public AddTemplateToGridView(ListItemType type, string colname)
{
_type = type;
_colName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_type)
{
case ListItemType.Item:
TextBox text = new TextBox();
text.ID = "txtAmount";
text.DataBinding += new EventHandler(txt_DataBinding);
container.Controls.Add(text);
break;
}
}
void txt_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
GridViewRow container = (GridViewRow)textBox.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _colName);
if (dataValue != DBNull.Value)
{
textBox.Text = dataValue.ToString();
}
}
}
So i have a gridview with textboxe's all open to edit at once
The problem is, when i click on Save button "which is outside gridview" all textboxe's gone
protected void btnSave_Command(object sender, CommandEventArgs e)
{
for (int nRow = 0; nRow < GridView1.Rows.Count; nRow++)
{
for (int nCol = 0; nCol < GridView1.Columns.Count; nCol++)
{
if (GridView1.Rows[nRow].Cells[nCol].Controls.Count == 0) continue;
//\\ --- Controls.Count always = 0
//\\ --- However each cell contain textbox
//\\ --- textbox disappear after save button clicked
TextBox txt = (TextBox)GridView1.Rows[nRow].Cells[nCol].Controls[0];
}
}
}
It looks like you are not creating the GridView after a postback, and the Save button is causing a postback. You need to dynamically create the GridView on each page load. Also, I have found this documentation on the ASP.NET page lifecycle helpful on numerous occasions.
In the documentation, you will see the slightly unintuitive reason why your code isn't working as you would like - btnSave_Command is not run until after a postback and Page_Load.

Custom Server Control with array of check boxes in asp.net doesn't main checkboxs state

I've created a server control that renders a list of check boxes.
The problem is that when I check some of the checkboxes and postback form all the check boxes gets unchecked.
Here is my server control class:
public class WeekControl : WebControl
{
public bool ShowCheckBoxs { get; set; }
public WeekControl()
{
ShowCheckBoxs = true;
Table = new Table();
Table.ID = "table1";
CheckBoxes = new CheckBox[7, 4];
Table.CssClass = "weekly";
}
protected override void OnInit(EventArgs e)
{
for (int i = 0; i < 6; i++)
{
TableRow tr = new TableRow();
Table.Rows.Add(tr);
for (int j = 0; j < 4; j++)
{
TableCell tc = new TableCell();
tr.Cells.Add(tc);
if (ShowCheckBoxs)
{
CheckBoxes[i, j] = new CheckBox();
CheckBoxes[i, j].ID = "ch" + i.ToString() + j.ToString();
tc.Controls.Add(CheckBoxes[i, j]);
}
}
}
}
public CheckBox[,] CheckBoxes;
public Table Table;
protected override void CreateChildControls()
{
Controls.Add(Table);
ChildControlsCreated = true;
base.CreateChildControls();
}
}
Any ideas?
Perhaps CreateChildControls comes after the step that deserializes the viewstate. Have you tried moving Controls.Add(Table) to OnInit?
You might find the MSDN article on ASP.NET page life cycle an interesting read. It mentions CreateChildControls only in the comment section.
The only comment on the CreateChildControls documentation page cautions against overriding the method. If it helps you, buy Roy Soliver a beer :)

Disable a checkbox created at runtime

In my asp.net application i have created checkboxes at runtime. I want to disable the checked checkbox when i click on a button. How do I achieve this? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Groove;
for (int j = 0; j < 18; j++)
{
tc = new TableCell();
tc.BorderStyle = BorderStyle.Groove;
ch = new CheckBox();
tc.Controls.Add(ch);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IDictionaryEnumerator RoleCheckBoxEnumerator = mRoleCheckBoxList.GetEnumerator();
while (RoleCheckBoxEnumerator.MoveNext())
{
CheckBox RoleCheckBox = (CheckBox)RoleCheckBoxEnumerator.Value;
string BoxRoleName = (string)RoleCheckBox.Text;
if (RoleCheckBox.Checked == true)
{
RoleCheckBox.Enabled = false;
break;
}
}
}
One rule-of-thumb while dealing with dynamically generated user controls is that you have to add them to the container on EVERY POSTBACK.
Just modify your code to generate the controls on every postback, and your code will start working like a charm!
EDIT
I am unsure what the ch variable is. I have assumed that its a checkbox. If I am correct, then all you have to do is to modify these lines
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
to this
//if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
EDIT 2
This is the code for generating 10 checkboxes dynamically -
protected void Page_Init(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = new CheckBox();
c.ID = "chk" + i.ToString();
c.Text = "Checkbox " + (i + 1).ToString();
container.Controls.Add(c);
}
}
Check the checkboxes when the page renders on the client side, click the button. This will cause a postback and the checkboxes will be generated again. In the click event of the button, you'll be able to find the checkboxes like this -
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = container.FindControl("chk" + i.ToString()) as CheckBox;
//Perform your relevant checks here, and disable the checkbox.
}
}
I hope this is clear.
Maybe
RoleCheckBox.Parent.Controls.Remove(RoleCheckBox);
You are not getting a proper reference to your checkboxes - mRoleCheckBoxList is not mentioned as part of your checkbox creation.
Try the following in your button event handler:
foreach (TableRow row in Table1.Rows)
foreach (TableCell cell in row.Cells)
{
CheckBox check = (CheckBox)cell.Controls[0];
if (check.Checked) check.Enabled = false;
}
Always when creating dynamic controls in .Net create them here:
protected override void CreateChildControls()
{
base.CreateChildControls();
this.CreateDynamicControls();
} //eof method
and in the PostBack find the them either from the event trigger or from a non-dynamic control:
/// <summary>
/// Search for a control within the passed root control by the control id passed as string
/// </summary>
/// <param name="root">the upper control to start to search for</param>
/// <param name="id">the id of the control as string</param>
/// <returns></returns>
public virtual Control FindControlRecursively(Control root, string id)
{
try
{
if (root.ID == id)
{
return root;
} //eof if
foreach (Control c in root.Controls)
{
Control t = this.FindControlRecursively( c, id);
if (t != null)
{
return t;
} //eof if
} //eof foreach
} //eof try
catch (Exception e)
{
return null;
} //eof catch
return null;
} //eof method

Resources