I want to create dynamic text box when user click on Add more link button.
For this I am using this code. And I have to mention that I am using master page.
protected void lnkAddMore_Click(object sender, EventArgs e)
{
if (Request.Cookies["value"] != null)
{
i = Convert.ToInt32(Request.Cookies["value"].Value) + 1 ;
}
for (int k = 1; k <= i; k++)
{
LiteralControl literal = new LiteralControl();
literal.Text = "<br /><br />";
Label newLabel = new Label();
newLabel.Text = "Choice" + " " + k.ToString();
newLabel.ID = "lblChoice_" + k.ToString();
newLabel.Attributes.Add("runat", "Server");
this.panelLabel.Controls.Add(newLabel);
this.panelLabel.Controls.Add(literal);
LiteralControl literal1 = new LiteralControl();
literal1.Text = "<br /><br />";
TextBox nexText = new TextBox();
nexText.ID = "txtChoice_" + k.ToString();
nexText.Attributes.Add("TextMode", "MultiLine");
nexText.Attributes.Add("runat", "Server");
panelTextbox.Controls.Add(nexText);
this.panelTextbox.Controls.Add(literal1);
Response.Cookies["value"].Value = i.ToString();
Session["Panel"] = panelTextbox;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Panel"] != null)
{
ContentPlaceHolder content=new ContentPlaceHolder();
content.Controls.Add(Session["Panel"] as Panel);
}
}
}
Now I am facing trouble how to retrieve the data of the these text boxes after the clicking on the submit button so that I can store the values of there text boxes to database.
What will be code written for the click event of btnSave
protected void btnSave_Click(object sender, EventArgs e)
{
if (Session["Panel"] != null)
{
ContentPlaceHolder content_new = new ContentPlaceHolder();
for (int i = 1; i <= count; i++)
{
strControlName = "txtChoice_" + i.ToString();
TextBox objTextBox = (TextBox)content_new.FindControl(strControlName);
strTextBoxValues[i] = objTextBox.Text;
string str3 = strTextBoxValues[2];
}
}
}
This code is showing error for objTextBox. The error is NullReferenceException.
How to write stored procedure for saving data of above code?
The main problem is handling the parameter declaration, how to declare dynamic parameter for passing values so that value is saved for dynamic textbox?
Thanks.
I have already answered it here.
Lost dynamically created text box values
You can try this.
private string GetValue(string ControlID)
{
string[] keys = Request.Form.AllKeys;
string value = string.Empty;
foreach (string key in keys)
{
if (key.IndexOf(ControlID) >= 0)
{
value = Request.Form[key].ToString();
break;
}
}
return value;
}
Then to get the value
string txtChoice1value = GetValue("txtChoice1");
First of all when you dynamically create a control it doesn't need to be set "runat = sever".
Problem is in this line `ContentPlaceHolder content_new = new ContentPlaceHolder();` you make a new ContentPlaceHolder, this mean it doesn't have any control to be found.
Check this page. How To Create TextBox Control Dynamically at Runtime
You need to find the reference of your already created ContentPlaceHolder like-
ContentPlaceHolder cnt =(ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
and then add the dynamically created Control in that ContentPlaceHolder as-
cnt.Controls.Add(Session["Panel"] as Panel);
Why you creating a new ContentPlaceHolder each time even when you have mentioned that you are using masterPage, so there must exists a ContentPlaceHolder..
Controls wont persist on postback have a look at http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
Related
I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net
I need to generate dynamic textboxes (upto 5-10 ) according to user response. So, what will be the best way to do it as regard performance,speed is concerned.
int n=5;
for (int i=0;i<n;i++)
{
TextBox MyTextBox=new TextBox();
//Assigning the textbox ID name
MyTextBox.ID = "tb" +""+ ViewState["num"] + i;
MyTextBox.Width = 540;
MyTextBox.Height = 60;
MyTextBox.TextMode = TextBoxMode.MultiLine;
this.Controls.Add(MyTextBox);
}
for MVC this link might help u...
http://www.codeproject.com/Articles/434886/Dynamically-adding-controls-on-a-hierarchical-stru
TRy this way
for (int j = 0; j < 10; j++)
{
//Create Dynamic textboxes with required field validator .
TextBox tbChildFirstName = new TextBox();
Label lblChildFirstName = new Label();
lblChildFirstName.ID = "lblChildFirstName" + j;
lblChildFirstName.Text = "Children FirstName";
lblChildFirstName.Width = 200;
lblChildFirstName.SkinID = "Outlabel";
tbChildFirstName.ID = "txtChildFirstName" + j;
tbChildFirstName.Text = "Hi hello";
pnlChildDetail.Controls.Add(lblChildFirstName);
pnlChildDetail.Controls.Add(tbChildFirstName);
RequiredFieldValidator rqf = new RequiredFieldValidator();
rqf.ID = "rqf" + i;
pnlChildDetail.Controls.Add(rqf);
rqf.ControlToValidate = "txtChildFirstName" + j;
rqf.ErrorMessage = "Children FirstName is required";
rqf.Display = ValidatorDisplay.Dynamic;
rqf.ValidationGroup = "EligibilityCheck";
rqf.SetFocusOnError = true;
rqf.Text = "*";
tbChildFirstName.Attributes.Add("runat", "server");
pnlChildDetail.Controls.Add(GetLiteral("<br/>"));
pnlChildDetail.Controls.Add(GetLiteral("<br/>"));
}
public Literal GetLiteral(string text)
{
Literal rv = default(Literal);
rv = new Literal();
rv.Text = text;
return rv;
}
Aspx
<asp:Panel ID="pnlChildDetail" Style="text-align: left; padding-left: 10px" Width="100%"
runat="server">
</asp:Panel>
More details for create dynamic textbox form database data count and how to get dynamic textbox value ?: see my blog
Here is a very helpful link and explained why
link from here
Always add the dynamic control in Page_PreInit()
Always assign ID when loading dynamically
For Example
protected void Page_PreInit(object sender, EventArgs e)
{
Control c= LoadControl("./WebUserControl2.ascx");
i=i+1;
c.ID= i.ToString();
PlaceHolder1.Controls.Add(c);
}
OR
protected void Page_PreInit(object sender, EventArgs e)
{
LinkButton button1 = new LinkButton();
button1.ID = "button1"
button1.Text = "button1"
PlaceHolder1.Controls.Add(button1);
}
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.
i have a gridview that has paging enabled. i also have a dropdown on the pager of the gridview where the user can select how many records per page they would like to retrieve. Once the dropdown is changed then an event is fired (shown below) to rerun the query with the updated results per page request. This works very well. I did however want to have a value "All" on the dropdown aswell and the method i used to impliment this is by disabling paging.
This all works brilliantly except for one issue. When the user selects "All" on the dropdown i would like to still show the pager once the gridview is updated. It doesnt show because i turned off paging but is there a way to show the pager again? See my code below for the event. (As you can see i renable the pager at the end but this has no effect)
thanks
damo
Code behind Event for Dropdown Change
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.AllowPaging = false;
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
Result fAuditOverallStatusLatest = new Result(sConn);
GridViewMain.DataSource = Result.getAuditOverallStatusLatest();
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
GridViewMain.BottomPagerRow.Visible = true;
GridViewMain.TopPagerRow.Visible = true;
}
DDL Code behind
protected void GridViewMain_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList GridViewMainddl = new DropDownList();
//adds variants of pager size
GridViewMainddl.Items.Add("5");
GridViewMainddl.Items.Add("10");
GridViewMainddl.Items.Add("20");
GridViewMainddl.Items.Add("50");
GridViewMainddl.Items.Add("100");
GridViewMainddl.Items.Add("200");
GridViewMainddl.Items.Add("500");
GridViewMainddl.Items.Add("All");
GridViewMainddl.AutoPostBack = true;
//selects item due to the GridView current page size
ListItem li = GridViewMainddl.Items.FindByText(GridViewMain.PageSize.ToString());
if (li != null)
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
GridViewMainddl.SelectedIndexChanged += new EventHandler(GridViewMainddl_SelectedIndexChanged);
//adds dropdownlist in the additional cell to the pager table
Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
TableCell cell = new TableCell();
cell.Style["padding-left"] = "15px";
cell.Controls.Add(new LiteralControl("Page Size:"));
cell.Controls.Add(GridViewMainddl);
pagerTable.Rows[0].Cells.Add(cell);
//add current Page of total page count
TableCell cellPageNumber = new TableCell();
cellPageNumber.Style["padding-left"] = "15px";
cellPageNumber.Controls.Add(new LiteralControl("Page " + (GridViewMain.PageIndex + 1) + " of " + GridViewMain.PageCount));
pagerTable.Rows[0].Cells.Add(cellPageNumber);
}
}
Put this in your Page_Init:
GridViewMain.PreRender += new EventHandler(GridViewMain_PreRender);
Then elsewhere in your Page class:
void GridViewMain_PreRender(object sender, EventArgs e)
{
var pagerRow = (sender as GridView).BottomPagerRow;
if (pagerRow != null)
{
pagerRow.Visible = true;
}
}
Then for your drop down event:
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
MyServices fServices = new FAServices(sConn);
Result fAuditOverallStatusLatest = new Result(sConn);
var data = Result.getAuditOverallStatusLatest();
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.PageSize = data.Count();
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
GridViewMain.DataSource = data;
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
}
In that PreRender event, you'll have to duplicate that code for the top pager.
Edit: To get All selected, make this change in GridViewMain_RowCreated:
if (li != null)
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
}
else
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.Count - 1;
}
Edit: if someone could also suggest a more sensible way to make what I'm trying below to happen, that would also be very appreciated
I'm building an multiPage form that takes a quantity (of product) from a POST method, and displays a form sequence relying on that number. when the user goes to the next page, the form is supposed to collect this information and display it (for confirmation), which will then send this info to a service that will supply URL's to display.
Needless to say, I'm having problems making this work. Here is the relevant parts of my (anonymised) code:
public partial class foo : System.Web.UI.Page
{
Int quantityParam = 3;
ArrayList Users = new ArrayList();
//the information for each user is held in a hashtable the array list will be an array list of the user hashtables
protected void Page_Init(object sender, EventArgs e)
{
if(null != Request["quantity1"])
{
this.quantityParam = Request["quantity1"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
int quantity = this.quantityParam;
if(quantity < 1){ mviewThankYou.SetActiveView(View4Error);}
else
{ //create a form for each user
mviewThankYou.SetActiveView(View1EnterUsers);
for(int user = 0;user < quantity; user++)
{
createUserForm(user);
}
}
}
protected void BtnNext1_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
for(int i = 0; i < quantity; i++)
{
String ctrlName = "txtUser" + i.ToString();
String ctrlEmail = "txtEmail" + i.ToString();
TextBox name = (TextBox)FindControl(ctrlName);
TextBox email = (TextBox)FindControl(ctrlEmail);
/*BONUS QUESTION: How can I add the Hashtables to the Users Array without them being destroyed when I leave the function scope?
this is where the failure occurs:
System.NullReferenceException: Object reference not set to an instance of an object. on: "tempUser.Add("name",name.Text);
*/
Hashtable tempUser = new Hashtable();
tempUser.Add("name",name.Text);
tempUser.Add("email",email.Text);
this.Users.Add(tempUser);
}
for(int i = 0; i < quantity; i++)
{
v2Content.Text +="<table><tr><td>Name: </td><td>"+
((Hashtable)Users[i])["name"]+
"</td></tr><tr><td>Email:</td><td>"+
((Hashtable)Users[i])["email"]+
"</td></tr></table>";
}
mviewThankYou.SetActiveView(View2Confirm);
}
}
private void createUserForm(int userNum){
DataTable objDT = new DataTable();
int rows = 2;
int cols = 2;
//create the title row..
TableRow title = new TableRow();
TableCell titleCell = new TableCell();
formTable.Rows.Add(title);
Label lblUser = new Label();
lblUser.Text = "<b>User "+ (userNum+1) + "</b>";
lblUser.ID = "lblTitle"+ userNum;
titleCell.Controls.Add(lblUser);
title.Cells.Add(titleCell);
for(int i = 0; i < rows; i++)
{
TableRow tRow = new TableRow();
formTable.Rows.Add(tRow);
for(int j = 0; j < cols; j++)
{
TableCell tCell = new TableCell();
if(j == 0){
Label lblTitle = new Label();
if(i == 0){
lblTitle.Text = "User Name:";
lblTitle.ID = "lblUser" + userNum;
}
else{
lblTitle.Text = "User Email:";
lblTitle.ID = "lblEmail" + userNum;
}
tCell.Controls.Add(lblTitle);
} else {
TextBox txt = new TextBox();
if(i==0){
txt.ID = "txtUser" + userNum;
}
else{
txt.ID = "txtEmail" + userNum;
}
RequiredFieldValidator val = new RequiredFieldValidator();
val.ID = txt.ID + "Validator";
val.ControlToValidate = txt.UniqueID;
val.ErrorMessage = "(required)";
tCell.Controls.Add(txt);
tCell.Controls.Add(val);
}
tRow.Cells.Add(tCell);
}//for(j)
}//for(i)
//create a blank row...
TableRow blank = new TableRow();
TableCell blankCell = new TableCell();
formTable.Rows.Add(blank);
Label blankLabel = new Label();
blankLabel.Text = " ";
blankLabel.ID = "blank" + userNum;
blankCell.Controls.Add(blankLabel);
blank.Cells.Add(blankCell);
}//CreateUserForm(int)
Sorry for the gnarly amount of (amateur code). What I suspect if failing is that FindControl() is not working, but I can't figure out why...
if any help can be given, I'd be very greatful.
Edit: showing the error might help:
Error (Line 112)
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 111: Hashtable tempUser = new Hashtable();
Line 112: tempUser.Add("name",name.Text);
Line 113: tempUser.Add("email",email.Text);
Line 114: this.Users.Add(tempUser);
You problem comes in the fact you are reloading the form every time in Page_Load. Make sure you only load the dynamic text boxes once and you will be able to find them when you need them for confirmation. As long as Page_Load rebuilds, you will not find the answer, and risk not finding anything.
I figured it out:
FindControl() works as a direct search of the children of the control it's called on.
when I was calling it, it was (automatically) Page.FindControl() I had nested the table creation inside a field and a Table control
when I called tableID.FindControl() it found the controls just as it should.
Thanks for the help, Gregory, and for all the comments everyone.
-Matt