how to get textbox value in placeholder on code behind? - c#

I created some textbox and I want to get their value dynamically.
Briefly, ı explain my page:
I have dropDown list has number 1 to 15.When the user select number and I created textbox as selected number.
for example; user select 3 and I create 3 text box and user write something in textbox.
Here is My Code:
aspx Side:
<asp:DropDownList ID="ddlUserSelected" AutoPostBack="true" OnSelectedIndexChanged="ddlUserSelected_SelectedIndexChanged" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
Code Behind:
protected void ddlUserSelected_SelectedIndexChanged(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
TextBox txtDate = new TextBox();
Label lbl = new Label();
lbl.Text = "<br/>";
txtDate .Width = 70;
txtDate .CssClass = "tbl";
txtDate .ID = "txtDate" + a;
PlaceHolder1.Controls.Add(txtDate);
PlaceHolder1.Controls.Add(lbl);
}
}
And Also I have Save button.
protected void btnSave_Click(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
//I want to get each textbox value
}
}
Note: for loop doesn't matter (can be removed) My main aim is get the text box value.
How to get textbox(es) value in btnSave_Click method?

Below code will help you
protected void ddlUserSelected_SelectedIndexChanged(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
TextBox txtDate = new TextBox();
Label lbl = new Label();
lbl.Text = "<br/>";
txtDate.Width = 70;
txtDate.CssClass = "tbl";
txtDate.ID = "txtDate" + a;
PlaceHolder1.Controls.Add(txtDate);
PlaceHolder1.Controls.Add(lbl);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
if(Request.Form.Get("txtDate" + a.ToString()) != null)
{
var str = Request.Form.Get("txtDate" + a.ToString());
}
}
}
If you are used master page then use below code
if (Request.Form.Get("ctl00$ContentPlaceHolder1$txtDate" + a.ToString()) != null)
{
var str = Request.Form.Get("ctl00$ContentPlaceHolder1$txtDate" + a.ToString());
}

protected void btnSave_Click(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
string value = Request.Form["txtDate" + a];
}
}

Problem
If you dynamically add controls to a page, you need to reloaded them on Page Init or Page Load.
Otherwise, you won't be able to find them when you post back.
ASPX
<asp:DropDownList ID="ddlUserSelected" AutoPostBack="true"
OnSelectedIndexChanged="ddlUserSelected_SelectedIndexChanged"
runat="server">
<asp:ListItem Text="Select one" />
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
<asp:ListItem Text="3" />
<asp:ListItem Text="4" />
<asp:ListItem Text="5" />
</asp:DropDownList>
<br/>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"/>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
Code Behind
private int Total
{
get
{
int total;
if (Int32.TryParse(ddlUserSelected.SelectedItem.Text, out total))
return total;
return 0;
}
}
protected void Page_Load(object sender, EventArgs e)
{
CreateTextBoxes(Total);
}
protected void ddlUserSelected_SelectedIndexChanged(object sender, EventArgs e)
{
CreateTextBoxes(Total);
}
protected void btnSave_Click(object sender, EventArgs e)
{
int total = Total;
for (int a = 1; a <= total; a++)
{
var textbox = PlaceHolder1.FindControl("txtDate" + a) as TextBox;
}
}
private void CreateTextBoxes(int total)
{
for (int a = 1; a <= total; a++)
{
// Make sure we do not add same ID again
if (PlaceHolder1.FindControl("txtDate" + a) == null)
{
TextBox txtDate = new TextBox();
Label lbl = new Label();
lbl.Text = "<br/>";
txtDate.Width = 70;
txtDate.CssClass = "tbl";
txtDate.ID = "txtDate" + a;
PlaceHolder1.Controls.Add(txtDate);
PlaceHolder1.Controls.Add(lbl);
}
}
}

Related

Looping Through a Dynamic Table and extract cell values c#

I am creating a dynamic table with X amount of rows and 2 columns. This is being stored in the view state.
How can I get the values of each cell per row?
Please see my code example:
<p>How many rows?<asp:TextBox ID="txtNoSitesDeployed" runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /></p>
<asp:Table ID="dt" runat="server">
</asp:Table>
<asp:Button ID="btnGenerateEmail" runat="server" Text="Generate Email Content Bulk" onclick="btnGenerateEmail_Click" />
<p>
<asp:Label ID="lblTemplate" runat="server" Text=""></asp:Label>
</p>
Please see code-behind:
public partial class _Default : System.Web.UI.Page
{
protected int Rows
{
get
{
return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
}
set
{
ViewState["Rows"] = value;
}
}
protected int Columns
{
get
{
return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
}
set
{
ViewState["Columns"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
this.Rows = Int32.Parse(txtNoSitesDeployed.Text);
this.Columns = 2;
}
}
protected void Button1_Click (object sender, System.EventArgs e)
{
// Total number of rows.
int rowCnt;
// Current row count.
int rowCtr;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter.
int cellCnt;
rowCnt = Rows;
for(rowCtr=1; rowCtr <= rowCnt; rowCtr++)
{
// Create a new row and add it to the table.
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
var txtSiteName = new TextBox();
txtSiteName.ID = "txtSiteName-" + rowCtr;
txtSiteName.ToolTip = "Enter site name";
cell1.Controls.Add(txtSiteName);
//add cell to row
row.Cells.Add(cell1);
TableCell cell2 = new TableCell();
var ddltBU = new DropDownList();
ddltBU.ID = "ddltBU-" + rowCtr;
ddltBU.Items.Add(new ListItem("fruit", "fruit"));
cell2.Controls.Add(ddltBU);
//add cell to row
row.Cells.Add(cell2);
//add row to dt
dt.Rows.Add(row);
}
}
protected void btnGenerateEmail_Click(object sender, EventArgs e)
{
foreach(TableRow row in dt.Rows)
{
foreach(TableCell cell in dt.Rows)
{
Response.Write(cell.Text);
}
}
}
}
I can't seem to access the cell values.
Any help would be greatly appreciated

asp.net content lost in dynamically generated table

I'm trying to use an ajax panel to add keep multiple images added to table cells dynamically. Thing is when I add the second image, the first one dissapears.
Its really just a silly example to try and get ajax controls working for another project.
I'm putting an image of Bill Gates in row 3, column 3 and an image of Steve Jobs in row 1, column 5. I have a button to place each image.
I can't seem to get both to display at the same time.
I have written a function to generate the cell id (GenerateTableCellID), as I've been told I would need to to this. Also there is a function to extract the cell and row in a tuple (GetColumnAndRow).
I'm not sure how to use a Session object to save the data. I thought using AJAX would be the answer, though I think I'm missing a major aspect of it.
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div id="tablePlaceHolder" runat="server"></div>
<asp:Button ID="tblButton2" runat="server" Text="Add Steve Jobs" OnClick="tblButton_Click_Jobs" />
<asp:Button ID="tblButton" runat="server" Text="Add Bill Gates" OnClick="tblButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
int tableSize = 5;
var t = new HtmlTable();
t.ID = "myTable";
var placeHolderURL = "http://wiki.tripwireinteractive.com/images/4/47/Placeholder.png";
for (int r = 0; r < tableSize; r++)
{
var tableRow = new HtmlTableRow();
tableRow.ID = "row_" + r.ToString();
for (int c = 0; c < tableSize; c++)
{
var tableCell = new HtmlTableCell();
var id = GenerateTableCellID(r, c);
tableCell.ID = id;
tableCell.Height = "20";
tableCell.Width = "20";
tableCell.InnerHtml = string.Format("<img src='{0}' width='20' height='20' />", placeHolderURL);
tableRow.Controls.Add(tableCell);
}
t.Controls.Add(tableRow);
}
tablePlaceHolder.Controls.Add(t);
}
protected void tblButton_Click(object sender, EventArgs e)
{
int c =2;
int r = 2;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://www.mnn.com/sites/default/files/billgates.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
cell.InnerHtml = "";
cell.Controls.Add(image);
}
protected Image GenerateImage(string url)
{
var image = new Image();
image.ImageUrl = url;
image.Width = 20;
image.Height = 20;
return image;
}
protected string GenerateTableCellID(int c, int r)
{
return "column_" + c.ToString() + "_row_" + r.ToString();
}
protected Tuple<int, int> GetColumnAndRow(string tableCellID)
{
string[] splitString = tableCellID.Split('_');
int column, row;
if (Int32.TryParse(splitString[1], out column) && Int32.TryParse(splitString[3], out row))
{
return new Tuple<int, int>(column, row);
}
else
{
return null;
}
}
It is because at every update you clear the html present before by cell.InnerHtml = ""; remove this and try
protected void tblButton_Click_Jobs(object sender, EventArgs e)
{
int c = 4;
int r = 0;
var id = GenerateTableCellID(c, r);
var image = GenerateImage("http://images.boomsbeat.com/data/images/full/209/jobs-jpg.jpg");
var cell = (HtmlTableCell)UpdatePanel2.FindControl(id);
//cell.InnerHtml = "";
cell.Controls.Add(image);
}
As mentioned on the Page LifyCycle your table is created everytime when you do reload page (does not matter is this postback or not). Also you could read this post. In other words, it is not proper way store your data in the dynamic generated controls, because you lose your data on page load.
But if it is necessary for you could use AJAX methods ($.get and $.post, not UpdatePanel) to get data from the backend and add this to generated control on the client side

How do I dynamically add a user control based on user input?

I have a user control (.ascx) added to my application:
<uc1:pomedsrow runat="server" id="POMedsRow" />
And here is html and logic
<asp:Panel ID="Panel1" runat="server">
How many PO Meds do you wish to order?
<asp:TextBox ID="txtReqPONum" runat="server" />
<asp:LinkButton ID="lbnAddPOMeds" runat="server" Text="Go"
OnClick="lbnAddPOMeds_Click"/>
</asp:Panel>
<asp:Panel ID="pnlPOMeds" Visible="false" runat="server">
<table border="1">
<tr>
<td><p>PO Meds</p></td>
<td><p>Min/Max</p></td>
<td><p>Amount to Order</p></td>
</tr>
<uc1:pomedsrow runat="server" id="POMedsRow" />
</table>
<br />
</asp:Panel>
protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
int ReqPO = Convert.ToInt32(txtReqPONum.Text);
int n = ReqPO;
for (int i = 0; i < n; i++)
{
Control pomedsrow = new Control();
//Assigning the textbox ID name
pomedsrow.ID = "txtPOAmount" + "" + ViewState["num"] + i;
this.Form.Controls.Add(pomedsrow);
}
}
But when I click the link button nothing happens. Am I not calling the custom control correctly?
You are not adding your control properly. Try this:
protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
TextBox txtReqPONum = (TextBox) Panel1.FindControl("txtReqPONum");
int ReqPO = 0;
if (txtReqPONum != null && int.TryParse(txtReqPONum.Text, out ReqPO) )
{
int n = ReqPO;
for (int i = 0; i < n; i++)
{
UserControl myControl = (UserControl)Page.LoadControl("~/pomedsrow.ascx");//(UserControl)Page.LoadControl("Your control path/pomedsrow.ascx");
//Assigning the textbox ID name
myControl.ID = "txtPOAmount" + "" + ViewState["num"] + i;
Panel1.Controls.Add(myControl);
}
}
}

Changing selection for a DropdownList triggers OnSelectedIndexChanged event of a CheckBoxList

Basically I want to implement a filtering option for a Grid view and I have a dropdown list containing the column names and a checkboxlist containing the available filtering values for that column. Every time I select a different column, I have to load the filtering values for that column into the checkbox list.
The problem I have is that when I change the column in the dropdown list, the event for the checklist is fired and the application crashes.
My controls are defined like this:
<div class="LeftAligned">
<asp:Label ID="FilterLabel" runat="server" Text="Filter by:" />
<asp:DropDownList runat="server" ID="FilterReviewsDropDownList" AutoPostBack="true" OnSelectedIndexChanged="FilterReviewsDropDownList_SelectedIndexChanged" />
<asp:ImageButton ID="FilterReviewsButton" runat="server" ImageUrl="~/images/filter.png" AlternateText="VALUE" CssClass="filter_button" OnClick="FilterReviewsButton_Click" />
<div onmouseout="javascript:bMouseOver=false;" onmouseover="javascript:bMouseOver=true;" class="filter_div">
<asp:CheckBoxList AutoPostBack="true" ID="FilterReviewsCheckBoxList" ClientIDMode="Static" runat="server" CssClass="filter_checklist collapsed"
OnSelectedIndexChanged="FilterReviewsCheckBoxList_Selected">
</asp:CheckBoxList>
</div>
<%--asp:Button runat="server" ID="ApplyFilterButton" Text="Apply Filter" OnClick="ApplyFilterButton_Click"/>
<asp:Button runat="server" ID="ClearFilterButton" Text="Clear Filter" OnClick="ClearFilterButton_Click"/--%>
</div>
In the CodeBehind file I have the following code:
protected void FilterReviewsButton_Click(object sender, EventArgs e)
{
FilterReviewsCheckBoxList.CssClass = "filter_checklist";
}
protected void FilterReviewsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFilterCheckboxes(FilterReviewsDropDownList.SelectedIndex);
}
private void LoadFilterCheckboxes(int iColumn)
{
SortedSet<string> oItems = new SortedSet<string>();
for (int i = 0; i < ReviewsGridView.Rows.Count; i++)
{
IEnumerable<Label> oLabels = ReviewsGridView.Rows[i].Cells[iColumn].Controls.OfType<Label>();
string sValue = "";
if (oLabels != null && oLabels.Count() > 0)
{
sValue = oLabels.First().Text;
}
else
{
sValue = ReviewsGridView.Rows[i].Cells[iColumn].Text;
}
if (!oItems.Contains(sValue))
oItems.Add(sValue);
}
FilterReviewsCheckBoxList.Items.Clear();
FilterReviewsCheckBoxList.Items.Add("All");
FilterReviewsCheckBoxList.Items[0].Selected = true;
foreach (string sItem in oItems)
{
FilterReviewsCheckBoxList.Items.Add(sItem);
FilterReviewsCheckBoxList.Items[FilterReviewsCheckBoxList.Items.Count - 1].Selected = true;
}
}
protected void FilterReviewsCheckBoxList_Selected(object sender, EventArgs e)
{
string sResult = Request.Form["__EVENTTARGET"];
if (string.IsNullOrEmpty(sResult))
{
FilterReviewsCheckBoxList.Items[0].Selected = true; //weird bug fix...
return;
}
string[] sCheckedBox = sResult.Split('$');
//get the index of the item that was checked/unchecked
int i = int.Parse(sCheckedBox[sCheckedBox.Length - 1].Split('_')[1]);
if (i == 0)
{
if (FilterReviewsCheckBoxList.Items[i].Selected == true)
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = true;
}
else
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = false;
}
}
else
{
if (FilterReviewsCheckBoxList.Items[i].Selected == false)
{
FilterReviewsCheckBoxList.Items[0].Selected = false;
}
else
{
//if (oFirstTable != null)
//{
// oTable = oFirstTable;
// oView = oTable.DefaultView;
//}
bool bAllChecked = true;
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
{
if (FilterReviewsCheckBoxList.Items[j].Selected == false)
{
bAllChecked = false;
break;
}
}
if (bAllChecked)
FilterReviewsCheckBoxList.Items[0].Selected = true;
}
}
}
Any idea of why FilterReviewsCheckBoxList_Selected is called (with the dropdownlist as the sender argument) when changing the dropdown list?
For anyone who may encounter the same problem, the fix is to avoid static binding of the grid view to entity data source. Instead, bind the grid dynamically in the page load event.

problem with binding expression for gridview

Suppose I have the below class
public partial class invoice
{
public list<lineitem> lineitem;
}
public partial class lineitem
{
private Quantity quantity = new Quantity();
public Quantity Quantity
{
get { return quantity; }
set { quantity = value; }
}
}
How do I bind the value to the gridview.
public void lbluom_OnDataBinding(object sender, System.EventArgs e)
{
for (int i = 0; i < invoicetransmit.Invoice.Count; i++)
{
Label lbl = (Label)sender;
lbl.Text =
invoicetransmit.Invoice[0].LineItem[i].Quantity.Value.ToString();
}
If I do this the values in the gridview are being overwritten with the latest values...and this one below
public void lbluom_OnDataBinding(object sender, System.EventArgs e)
{
for (int i = 0; i < invoicetransmit.Invoice.Count; i++)
{
Label lbl = (Label)sender;
lbl.Text = Eval("Value")
} property does not exist.
}
}
This is how i added values to the grid
public void Addtogrid()
{
//var lineItems = (Session["BillXML"] as InvoiceTransmission).Invoice[0].LineItem;
invoicetransmit.Invoice[0].LineItem.Add(new LineItem {MaterialCode = MaterialCode.Text, ChargeCode = ChargeCode.Text, CostCenter = CostCenter.Text, GLAccount = GLAccount.Text });
//lineItems.Add(new LineItem { MaterialCode=MaterialCode.Text,ChargeCode=ChargeCode.Text,CostCenter=CostCenter.Text,GLAccount=GLAccount.Text});
for (int i = 0; i < invoicetransmit.Invoice[0].LineItem.Count; i++)
{
invoicetransmit.Invoice[0].LineItem[i].Quantity.UOMCode = UOM.Text;
invoicetransmit.Invoice[0].LineItem[i].Quantity.Value = Convert.ToDecimal(Quantity.Text);
invoicetransmit.Invoice[0].LineItem[i].UnitPrice.Value = Convert.ToDecimal(Price.Text);
//invoicetransmit.Invoice[0].LineItem[i].TotalNetAmount = (invoicetransmit.Invoice[0].LineItem[i].Quantity.Value) * (invoicetransmit.Invoice[0].LineItem[i].UnitPrice.Value);
invoicetransmit.Invoice[0].LineItem[i].TotalNetAmount = ( Convert.ToDecimal(Quantity.Text) )* (Convert.ToDecimal(Price.Text));
GridView1.DataSource = invoicetransmit.Invoice[0].LineItem;
// GridView1.DataSource = lineItems;
GridView1.DataBind();
//}
Please help me resolve this question
Try the RowDataBound event
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label) e.Row.FindControl("Label1");
if(lbl!=null)
{
lbl.Text = invoicetransmit.Invoice[0].LineItem[e.Row.RowIndex].Quantity.Value.ToString();
}
}
}

Categories

Resources