ASP.NET C#.
Inside UpdatePanel we have TextBox with OnTextChanged="text_changed" method and Panel.
if number 3 was typed at textbox, 3 textboxes below will appear inside Panel with different IDs.
However when button outside updatepanel clicks, dynamically created textboxes not found error occured.
How to get values of dynamically created textboxes?
Creating textbox:
protected void text_changed(Object sender, EventArgs e)
{
int n = Int32.Parse(TextBox6.Text);
Table table = new Table();
for (int i = 0; i < n; i++)
{
TableRow trow = new TableRow();
table.Rows.Add(trow);
TableCell tcell = new TableCell();
tcell.Text = (i + 1).ToString();
TextBox tb = new TextBox();
tb.ID = "TB" + i.ToString();
tcell.Controls.Add(tb);
trow.Cells.Add(tcell);
}
Panel1.Controls.Add(table);
ButtonClick //get values from created textboxes:
int n = Int32.Parse(TextBox6.Text);
for (int i = 0; i < n; i++)
{
string title = ((TextBox)UpdatePanel1.FindControl("Panel1").FindControl("TB" + i.ToString())).Text; //here null pointer exception..
}
where are you generating your textboxes? if you're creating them in text_changed event, then on the next post back your going to run into pagelife cycle issues. you'd need to cache the fact that you created them, and recreate them in the OnInit phase of the page.
Related
I am creating a total of n textbox whenever i enter the value n on a textbox and click on a button in ASP.NET. Im using the below code for that,
int n = Convert.ToInt32(text_flats_blocks.Text);
for (int i = 0; i < n; i++)
{
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "text_" + (i+1);
panel_flats_blocks.Controls.Add(MyTextBox);
MyTextBox.CssClass = "textblock";
Literal lit = new Literal();
lit.Text = "<br /><br />";
panel_flats_blocks.Controls.Add(lit);
}
This works fine and the textboxes are created. Then i enter some values to the textboxes and click on another button. On clicking the second button the values entered in the textboxes should be obtained using C#. But i have created ID for these textboxes using variables like this text_ + (i+1) that creates the names as text_1, text_2 etc. How can i use this as an ID to access the textbox value like id.Text but here the id contains variable. I want to use loop to iterate for n times and access all values from all n textboxes and store them in a list. How can i do this using C#?
You can use FindControl Method
public void SecondButton_Click(object sender, EventArgs)
{
int n = Convert.ToInt32(text_flats_blocks.Text);
for (int i = 0; i < n; i++)
{
var control= (TextBox)FindControl("text_" + (i+1));
//now you have the controls and you can do whatever you want with them
}
}
I have searched for a while but can never get a clear answer on the correct way of doing this, or even if it is possible.
I am grabbing 2 rows from a table in SQL, returning them in a DataTable. I iterate through the rows and dynamically create a div for that row and then a label for each column with the stored value, and then repeats the process for the next row.
All I am missing to make it work is storing the labels into a List to bring back to the placeholder that the div will be created in.
here is a snippet... also, I want to do it this way, not with a gridview or tables for learning purposes and I already know how to use the gridview and table to do this. I have a total of 7 columns in this SQL table, and could have an unlimited number of rows.
EDIT
public void AddDiv(DataTable gameData)
{
for (int i = 0; i < gameData.Rows.Count; i++)
{
//newControl.InnerHtml = AddLabel(gameData, i);
//PlaceHolder1.Controls.Add(newControl);
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "div" + i++;
Label lblTitle = new Label();
lblTitle.Text = gameData.Rows[i]["Game_Title"].ToString();
this.Controls.Add(lblTitle);
PlaceHolder1.Controls.Add(lblTitle);
Label lblPublisher = new Label();
lblPublisher.Text = gameData.Rows[i]["Game_Publisher"].ToString();
this.Controls.Add(lblPublisher);
PlaceHolder1.Controls.Add(lblPublisher);
Label lblGenre = new Label();
lblGenre.Text = gameData.Rows[i]["Game_Genre"].ToString();
this.Controls.Add(lblGenre);
PlaceHolder1.Controls.Add(lblGenre);
Label lblESRB = new Label();
lblESRB.Text = gameData.Rows[i]["Game_ESRB"].ToString();
this.Controls.Add(lblESRB);
PlaceHolder1.Controls.Add(lblESRB);
Label lblUserRating = new Label();
lblUserRating.Text = gameData.Rows[i]["Game_UserRating"].ToString();
this.Controls.Add(lblUserRating);
PlaceHolder1.Controls.Add(lblUserRating);
Label lblWebsite = new Label();
lblWebsite.Text = gameData.Rows[i]["Game_Website"].ToString();
this.Controls.Add(lblWebsite);
PlaceHolder1.Controls.Add(lblWebsite);
}
}
First off, the InnerHtml property of the HtmlGenericControl is a string. Your code is assigning the result of a void method to this property. I think what you want to do is create the div and pass a reference to that to the AddLabel method. Here you can create your labels and add them to the div's Control's property. Finally, add your div to the Placeholder as you currently do. Hopefully, this will get you on the right track.
protected void Page_Load(object sender, EventArgs e)
{
AddDiv();
}
public void AddDiv()
{
for (int i = 0; i < 5; i++)
{
HtmlGenericControl newControl = new HtmlGenericControl("div");
newControl.ID = "div" + i;
AddLabel(newControl, i);
PlaceHolder1.Controls.Add(newControl);
}
}
protected void AddLabel(HtmlGenericControl control, int i)
{
Label lblTitle = new Label();
lblTitle.Text = "label" + i.ToString();
control.Controls.Add(lblTitle);
Label lblPublisher = new Label();
lblPublisher.Text = "publisherLabel" + i.ToString();
control.Controls.Add(lblPublisher);
}
I am doing a crossword puzzle and i have 100 text boxes in a panel like this :
Every text box have an id of 00 - 99 since there is 100 of it .
First Row will have an id 00-09 , 2nd row will have an id of 10-19 and so on.
When user types something in some text box will be null and some text box will have values in it. How do I save values from a text box of a certain id to a database? For example the above image, HELP, text box id of 22 will have the value H , id of 23 will have the value of E , id of 24 will have value of L , id of 25 will have value of P.
I don't want to save the null values of the text box , I want to save values of the textboxes which are not null. I also need to take into account their textbox ids so that when I populate them back, I just have to insert them through ID .
I am new to C# , appreciate any help/advise/solutions on this.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
//hw.Write("<table>");
for (int i = 0; i <= 9; i++)
{
//hw.Write("<tr>");
for (int j = 0; j <= 9; j++)
{
TextBox tb = new TextBox();
tb.MaxLength = (1);
tb.Width = Unit.Pixel(40);
tb.Height = Unit.Pixel(40);
tb.ID = i.ToString() + j.ToString(); // giving each textbox a different id 00-99
Panel1.Controls.Add(tb);
}
Literal lc = new Literal();
lc.Text = "<br />";
Panel1.Controls.Add(lc);
}
}
protected void btnShow_Click(object sender, EventArgs e)
{
foreach (Control control in Panel1.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
if (string.IsNullOrEmpty(textBox.Text))
{
textBox.Style["visibility"] = "hidden";
}
// textBox.Enabled = false;
textBox.Text = "";
}
}
}
The proper way to do this is to wrap these textboxes inside a Repeater or Datalist controls. You can ready about these controls from here. This way when number of rows increase you will not have to change to your loop or hard-coded values.
As for your question to store values for a given Id, you can define row# and col# in your database and sort on row# and col#, this should work.
The easiest way is to make a 2D array (or List) of your TextBoxes. In where you create your TextBoxes:
List<List<TextBox>> textBoxList = new List<List<TextBox>>();
for (int i = 0; i <= 9; i++)
{
List<TextBox> textBoxRow = new List<TextBox>(); //this could be columns, not sure
for (int j = 0; j <= 9; j++)
{
TextBox tb = new TextBox();
....
textBoxRow.Add(tb);
}
...
textBoxList.Add(textBoxRow);
}
Now you can read/write to those array entries, such as:
string readValue = textBoxList[2][5].Text;
textBoxList[1][7].Text = "asdf";
HI I have requirement that
1) display given no.of textboxes dynamically and save to DB
2) if I change the number then new textboxes should append to UI
EX: TextBox AddButton
If I give 2 in textbox and click on add
Then 2 textboxes should appear. I filled some data in those textboxes. Now When I change the value 2 to 5 then 3 more textboxes should append(condition:old textboxes data should retain)
If the second value is less than or equal to first value then do nothing.
My code is
void Append()
{
string Data = string.Empty;
TextBox tb;
if (Convert.ToInt32(hdnCnt.Value) < Convert.ToInt32(txtNoofGames.Text))
{
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
if (i <= Convert.ToInt32(hdnCnt.Value))
{
tb = (TextBox)Form.FindControl("txtGame1");
Data = tb.Text;
}
TextBox Newtb = new TextBox();
Newtb.ID = "txtGame" + i;
Form.Controls.Add(Newtb);
if (i <= Convert.ToInt32(hdnCnt.Value))
{
Newtb.Text = Data;
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (hdnCnt.Value != "")
Append();
hdnCnt.Value = txtNoofGames.Text;
for (int i = 0; i < Convert.ToInt16(txtNoofGames.Text); i++)
{
TextBox tb = new TextBox();
tb.ID = "txtGame" + i;
Form.Controls.Add(tb);
}
}
I am getting exception "object reference not set to an instance of object" at Data = tb.Text; in append method.
You didn't initialize it from the looks of it
TextBox tb = new TextBox();
Hope that helps,
Instead of Form.Controls.Add(tb);
Please try with Page.Form.Controls.Add(tb);
i have a page where i create 2 checkboxes dynamically.
TableRow tr = new TableRow();
for (int i = 0; i < 2; i++)
{
TableCell Tc = new TableCell();
Tc.Attributes["style"] = "line-height: 30px; text-align: left";
Tc.Attributes["width"] = "50%";
Tc.Style.Add("padding-left", "5px");
//Checkboxes on left along with labels
CheckBox checkBoxCtrl = new CheckBox();
checkBoxCtrl.ID = "checkBoxCtrl" + i;
Tc.Controls.Add(checkBoxCtrl);
tr.Cells.Add(Tc);
}
once they are created in the page load event i have a Ok_button click event which requires to check if the checkbox is checked or not.
protected void Update2_Click(object sender, EventArgs e)
{
if(checkBoxCtrl.checked)
//here i wont be able to get the value
// i get the error the name checkBoxCtrl does not exist..
{
response.write("true");
}
}
but how do i do the check in this case.
thanks
Answer:
this is what needs to be done to get the checkbox values
protected void Update1_Click(object sender, EventArgs e)
{
for(int i = 0; i < ControlPropList.Count; i++)
{
CheckBox chkTest = (CheckBox)xxx.FindControl("checkBoxCtrl" + i);
{
if (chkTest.Checked)
{
Global.logger.Info("Checkbox True = " + chkTest.ID);
}
else
{
Global.logger.Info("Checkbox False = " + chkTest.ID);
}
}
}
}
This should work fine as long as you add the checkboxes to your page in the Page_PreInit method. If you add them after that (Page_Load for example), their values will not be maintained.
Read about the asp.net page lifecycle here:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Consider storing the dynamic checkbox in a local member:
private CheckBox _myCustomCheckbox = new CheckBox();
protected override void OnInit(EventArgs e)
{
TableRow tr = new TableRow();
for (int i = 0; i < 2; i++)
{
TableCell Tc = new TableCell();
if (i == 0)
{
Tc.Attributes["style"] = "line-height: 30px; text-align: left";
Tc.Attributes["width"] = "50%";
Tc.Style.Add("padding-left", "5px");
//Checkboxes on left along with labels
_myCustomCheckbox.ID = "checkBoxCtrl" + j;
Tc.Controls.Add(_myCustomCheckbox);
tr.Cells.Add(Tc);
}
}
// the row needs added to a page control so that the child control states can be loaded
SomeTableOnThePage.Controls.Add(tr);
base.OnInit(e);
}
protected void Update2_Click(object sender, EventArgs e)
{
if(_myCustomCheckbox.Checked)
{
response.write("true");
}
}
May not be quite what you want, but I had a similar issue, I have a dynamically generated table in ASP.NET page, with dynamically generated CheckBoxes in one column. I have created the data for the table from a collection, and then as the dynamic CB's are created I give them an ID and store them in a second collection, such as an array of CB's.
So when I need to find the Checked value I simply iterate through the collection, and I can find the ones that are Checked.
Also as they were created simultaneously with the data in the dynamic table I was able to easily tie the table data row to the Checkbox value.
This obviously assumes that the dynamic table and CB's were created using some kind of looping.
This may not be the best solution but works for my current needs.