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

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);
}
}
}

Related

How to populate html block several times asp.net

I would like to make a kanban for my application. I want to populate it with a mysql table. To do so I need to repeat the following lines of code several times.
<li class="drag-column drag-column-needs-review" id="list2" runat="server">
<span class="drag-column-header" runat="server" id="listspan">
<asp:Label ID="Label3" runat="server" Text="Label">Needs Review</asp:Label>
</span>
<div class="drag-options" id="options3"></div>
<ul class="drag-inner-list" runat="server" id="list1">
</ul>
</li>
How can I do so? I am unsure what to do in aspx.cs Here is what I have tried so far.
protected void Page_Load(object sender, EventArgs e)
{
PopulateLists();
}
public void PopulateLists()
{
HtmlGenericControl li;
for (int j = 0; j < 5; j++)
{
li = new HtmlGenericControl("li");
li.Attributes.Add("class", "drag-column drag-column-needs-review");
li.InnerText = "Item" + j;
list2.Controls.Add(li);
li.Style.Add("background-color", "green");
for (int i = 0; i < 3; i++)
{
li = new HtmlGenericControl("li");
li.Attributes.Add("class", "drag-item");
li.InnerText = "Item" + i;
if (i % 2 == 0)
{
li.Style.Add("background-color", "#ffff00");
}
else
{
li.Style.Add("background-color", "red");
}
list1.Controls.Add(li);
list1.Attributes.Add("onclick", "return ShowModalPopup()");
}
}
}
The code above gives my a list with rows but only for the first list the other lists are not being populated.
the red arrows in images is what I want to do. Any help would be very appreciated thank you.

c# asp.net for append int value to the label id

I have the following label with ids:
<asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server" Visible="true"></asp:Label>
I want to assign the values to the label ids using for loop.
I am using the following tags in c#:
for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}
But ‘Find’ shows error like below:
System.Web.UI.ControlCollections does not have the definition for ‘Find’. But I have already added ‘System.Web.UI’ dll file. Can anyone help me?
I am using dotnet framework 4.0.
Thanks in Advance.
You can do this like this
public Control[] FlattenHierachy(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(FlattenHierachy(control));
}
}
return list.ToArray();
}
and
protected void Page_Load(object sender, EventArgs e)
{
Control[] allControls = FlattenHierachy(Page);
foreach (Control control in allControls)
{
Label lbl = control as Label;
if (lbl != null && lbl.ID == "FromName0")
{
lbl.ID = "myid";//Do your like stuff
}
}
}
Just use : Here MSDN article about FindControl
//
// Summary:
// Searches the page naming container for a server control with the specified identifier.
//
// Parameters:
// id:
// The identifier for the control to be found.
//
// Returns:
// The specified control, or null if the specified control does not exist.
public override Control FindControl(string id);
Here how your code should look like. Just as advice check if the control is null or the session variable is null, this can give you an exception.
for (int i = 0; i < count; i++)
{
var label = FindControl("FromName " + i) as Label;
if(label == null || Session["DeliverAddress" + i] == null)
continue;
label.Text = Session["DeliverAddress" + i].ToString();
}

Select item from a drop down list, remove item from list as a value then update a total

I am trying to use asp.net and C#
I want to create a variable that has a given value of 10.
lets call this variable pool
I then want to be able to select a number between 1 and 10 from a dropdownlist.
Lets say i select 5 from the ddl
Then 5 should be subtracted from the pool which would leave pool displaying 5.
If i want to go back and select another number from the dropdown list I want to be able to only see the numbers that I can subtract from pool.
I.E i cant choose 6 as there is only 5 left in the pool.
Please help
Is it that hard?
The explanation as per the code comment below
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
My Pool : <asp:Label ID="lbl" runat="server" Text="10"></asp:Label><br />
<asp:HiddenField ID="hf" runat="server" Value="10" />
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl" />
</Triggers>
</asp:UpdatePanel>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("Count");
// Loop
for (int i = 0; i < 11; i++)
dt.Rows.Add(i);
// Bind to Drop Down
ddl.DataSource = dt;
ddl.DataTextField = "Count";
ddl.DataValueField = "Count";
ddl.DataBind();
// Dispose
dt.Dispose();
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// Variable
int myPool = 0;
int mySelectedValue = 0;
int result = 0;
int dropDownValue = 0;
bool isInteger = false;
// Parse Integer
int.TryParse(hf.Value, out myPool);
int.TryParse(ddl.SelectedValue, out mySelectedValue);
// Set Result
result = myPool - mySelectedValue;
// Set to Hidden Value
hf.Value = result + "";
lbl.Text = result + "";
foreach (ListItem item in ddl.Items)
{
// Reset
isInteger = false;
dropDownValue = 0;
// Parse Drop Down Value
isInteger = int.TryParse(item.Value, out dropDownValue);
// Check
if (isInteger)
{
// Ensure is not less than 0, If less than 0 disabled the selected value
if ((result - dropDownValue) < 0)
item.Enabled = false;
}
}
}

how to get textbox value in placeholder on code behind?

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);
}
}
}

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.

Categories

Resources