I'm having problems with finding my controls in my dynamically created literal control. I want to be able to grab the value in the label with the fnameID(x) id.
ASPX:
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label lbl = (Label)Panel1.FindControl("fnameID0");
Response.Write(lbl.Text);
}
Currently I am getting the following error when I click on the button:
Object reference not set to an instance of an object.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
{
Label lbl = (Label)Page.FindControl("fnameID0");
**Response.Write(lbl.Text);**
}
Try explicitly setting the ID of the control you generate:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
LiteralControl dynLabel = new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>");
dynLabel.ID = "fnameID" + i.ToString();
Panel1.Controls.Add(dynLabel);
}
}
You're getting the null reference exception because no control with the specified ID is being found, so FindControl is returning null, and you can't get the Text property of a null.
Related
Does anyone know how I can add a control dynamically inline with innerhtml from code behind then capture the value when a button is clicked? Not sure how to explain this so I created example code.
.aspx
<div id="myTable" runat="server"></div>
<div id="result" runtat="server"></div>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
.cs
protected void Page_Load(object sender, EventArgs e)
{
GetTable();
}
protected void GetTable()
{
string name = "Sam";
string age = "18";
TextBox txtTags = new TextBox();
txtTags.ID = "txtBox1";
myTable.InnerHtml =
"<div>" +
"<div>" +
name +
"</div>" +
"<div>" +
Controls.Add(txtTags) +
"</div>" +
"<div>" +
age +
"</div>" +
"</div>";
}
protected void btnSave_Click()
{
string myTextbox = txtBox1.Text;
result.InnerHtml = "Result: " + myTextbox;
}
Alright I figured it out.
TextBox txtFileTags = new TextBox();
txtTags.ID = "txtBox1";
HtmlGenericControl parent1 = new HtmlGenericControl("div");
HtmlGenericControl child1 = new HtmlGenericControl("div");
HtmlGenericControl child2 = new HtmlGenericControl("div");
HtmlGenericControl child3 = new HtmlGenericControl("div");
HtmlGenericControl child4 = new HtmlGenericControl("div");
child1.InnerHtml = "Sam"
parent1.Controls.Add(child1);
child2.Controls.Add(txtTags);
parent1.Controls.Add(child2);
child3.InnerHtml = "18";
parent1.Controls.Add(child3);
myTable.Controls.Add(parent1);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetTable();
}
}
void GetTable()
{
string name = "Sam";
string age = "18";
string input = $#"
<div>
<div>{name}</div>
<div><input type='text' name='txtBox1' value='' /></div>
<div>{age}</div>
</div>";
myTable.InnerHtml = input;
}
protected void btnSave_Click(object sender, EventArgs e)
{
string myTextbox = Request.Form["txtBox1"] + "";
result.InnerHtml = "Result: " + myTextbox;
}
Within a site using a MasterPage, I have a page which has an UpdatePanel. Inside that, there is a ListBox which contains a list of users. There is also a dynamically generated list of checkboxes, which should have different values checked based upon which user is selected.
It works great the first time you select a user. However, when you select a second user, the original values remain - you see the checkboxes of both users checked.
.aspx
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>Access Database Security Controls</h1>
<asp:UpdatePanel ID="SecurityControls" runat="server">
<ContentTemplate>
<asp:ListBox ID="AccessUsers" runat="server" Rows="15" SelectionMode="Single" OnSelectedIndexChanged="AccessUsers_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>
<asp:PlaceHolder ID="SecurityRoles" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
code behind
protected void Page_Load(object sender, EventArgs e)
{
LoadAllRoles();
}
protected void LoadAllRoles()
{
for (int i = 0; i < 4; i++)
{
Label lbl = new Label();
lbl.ID = "lbl_" + i.ToString();
lbl.Text = i.ToString() + " lbl text here";
SecurityRoles.Controls.Add(lbl);
CheckBox cb = new CheckBox();
cb.ID = "cb_" + i.ToString();
SecurityRoles.Controls.Add(cb);
SecurityRoles.Controls.Add(new LiteralControl("<br />"));
}
}
protected void AccessUsers_SelectedIndexChanged(object sender, EventArgs e)
{
Control page = Page.Master.FindControl("MainContent");
Control up = page.FindControl("SecurityControls");
Control ph = up.FindControl("SecurityRoles");
CheckBox cbRole = (CheckBox)ph.FindControl("cb_" + AccessUsers.SelectedValue);
if (cbRole != null)
cbRole.Checked = true;
}
I've tried doing cb.Checked = false; when I am creating the checkboxs, but even on the partial postbacks, the SecurityRoles placeholder control starts out empty.
How do I get the checkboxes to clear?
You can try to uncheck all other check-boxes before you check one.
foreach (Control c in ph.Controls)
{
if(c is CheckBox)
{
((CheckBox)c).Checked=false;
}
}
I am quite new to ASP and I have been stuck on an issue for about a week. The issue is probably something to do with the Asp Page Life Cycle but I am unable to find how this can be resolved. The issue is that skipto(..) is never called when I click the LinkButton (that were created on first Page Load), which means the LinkButtons are not rendered.
Sample Code below:
// Code Behind
protected void Page_Load(object sender, EventArgs e)
{
loadData();
if (!Page.IsPostBack)
{
skiptof();
}
}
public void loadData() {
// Loads from database
}
public void skipto(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn != null)
{
if (btn.CommandArgument != null && btn.CommandArgument != "0")
{
int currPage = 1;
int.TryParse(btn.CommandArgument, out currPage);
skiptof(currPage);
}
}
}
public void skiptof(int currPage = 1)
{
int lastPage = // calculate from LoadData()
string pageDisabled = "";
// pages
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage)
{
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "")
{
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
pagesPageLink.Click += new EventHandler(skipto);
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
// page
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel runat="server" id="UpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<div id="details" runat="server"></div>
<div class="pagination text-center" id="pagination" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
Your problem is:
You didn't bind the data again on postback, I've modified your code a little bit, there are several problems:
in the method skipof:
public void skiptof(int currPage = 1) {
//Clear the controls here then add them again
pagination.Controls.Clear();
int lastPage = // calculate from LoadData()
string pageDisabled = "";
HtmlGenericControl ul = new HtmlGenericControl("ul");
while (pageCount <= lastPage) {
// Disable the current page
pageDisabled = pageCount == currPage ? " class=\"disabled\"" : "";
HtmlGenericControl pagesli = new HtmlGenericControl("li");
if (pageDisabled != "") {
pagesli.Attributes.Add("class", "disabled");
}
LinkButton pagesPageLink = new LinkButton();
// you can directly assign the method to be called here, there is no need to create a new EventHandler
pagesPageLink.Click += PagesPageLink_Click;
pagesPageLink.CommandArgument = pageCount.ToString();
pagesPageLink.Text = pageCount.ToString();
pagesli.Controls.Add(pagesPageLink);
ul.Controls.Add(pagesli);
pageCount += 1;
}
pagination.Controls.Add(ul);
}
You didn't bind the data again in postback, so I modified it:
Page Load:
protected void Page_Load(object sender, EventArgs e) {
//Remove the Page.IsPostBack checking
skiptof();
}
Please take note that the controls you added dynamically will be cleared and you have to add it again on postback to avoid data lost.
Then you'll be able to get the value on PagesPageLink_Click event:
The whole sample is here:
http://pastie.org/10503291
I have a somewhat complicated setup for an ASP.NET TextBox. It is inside of a user control that's inside a repeater that's inside a repeater.
I am able to load text into the TextBox and also get TextChanged to fire when text is changed to anything EXCEPT FOR blank/empty. The event doesn't fire when the user clears out the TextBox.
Does anyone know why ASP.NET might discriminate between text and blank?
I made a simplified version of my problem to separate it from possible other factors. I get the same results.
Below is my aspx markup:
<div>
<asp:Repeater runat="server" ID="rptRepeat" EnableViewState="False">
<ItemTemplate>
<asp:repeater runat="server" ID="rptChild" EnableViewState="False">
<ItemTemplate>
<uc:Things runat="server" ID="ucChild"></uc:Things>
</ItemTemplate>
</asp:repeater>
</ItemTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="btnBtn" Text="click"/>
Below is my user control markup
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
Below is the aspx code behind
private List<List<TestObj>> data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.rptRepeat.ItemCreated += rptRepeat_ItemCreated;
this.rptRepeat.ItemDataBound += rptRepeat_ItemDataBound;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Session["data"] = data = new List<List<TestObj>>();
for (var x = 0; x < 5; x++)
{
data.Add(new List<TestObj>());
for (var y = 0; y < 5; y++)
{
data[0].Add(new TestObj
{
Text = x + "_" + y
});
}
}
}
else
{
data = (List<List<TestObj>>)Session["data"];
}
this.rptRepeat.DataSource = data;
this.rptRepeat.DataBind();
}
void rptRepeat_ItemCreated(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
rptChild.ItemDataBound += rptChild_ItemDataBound;
}
void rptRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var rptChild = (Repeater)e.Item.FindControl("rptChild");
var rowObj = (List<TestObj>)e.Item.DataItem;
rptChild.DataSource = rowObj;
rptChild.DataBind();
}
void rptChild_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var ucChild = (WebUserControl1)e.Item.FindControl("ucChild");
var rowObj = (TestObj)e.Item.DataItem;
ucChild.data = rowObj;
}
Below is the user control code behind
public TestObj data = null;
protected void Page_Init(object sender, EventArgs e)
{
this.txtText.TextChanged += txtText_TextChanged;
}
protected void Page_PreRender(object sender, EventArgs e)
{
this.txtText.Text = data.Text;
}
void txtText_TextChanged(object sender, EventArgs e)
{
data.Text = this.txtText.Text;
}
You can download the whole project at https://www.dropbox.com/s/p6zkqqsw71fvuyw/textchangetest.zip?dl=0 if you want to try tinkering with stuff to get me an answer.
The databinding of the repeater was intentionally put in Page_Load because otherwise child controls' events don't fire.
I created a dynamic button inside c# code and I have assigned some value in button.text but the problem is that on buttn_Click event I want to show details related to that value. So any idea how to do this?
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < list.Count; i++)
{
lnk1 = new Button();
VW obj1 = list[i];
lnk1.Text = " "+obj1.ticketNo+": "+obj1.subject+": "+obj1.qu;
lnk1.Click += new EventHandler(lnk1_Click);
}
}
I want to show above mentioned obj1.ticketno in next page like ticket No: some value is selected
You could retrieve the reference to the button using the sender parameter of the event handler and cast the value to the Button type.
In lnk1_Click event handler you can get the link by type casting the sender to Button type and get the link text. Using that you can retrieve ticket number for which click has been done.
Something like this:
void lnk1_Click(object sender)
{
Button clickedLinkButton = sender as Button;
String buttonText = clickedLinkButton .Text;
String clickedTicketNumber =
buttonText
.SubString(0, buttonText.IndexOf(':'))
.Trim();"
}
Here is the sample code segment
protected void lnk1_Click(object sender, EventArgs e)
{
Button bt = sender as Button;
bt.Text;
}
you can use GridView or Repeater and in Iteme Template you can put button. and bind perticular grid or repeater.
<asp:repeater runat="server" id="rpt">
</ItemTemplate>
<asp:LinkButton runat="serevr" ID="lbtnLInkButton" CommandArgument='<%#Eval("ID") %>' CommandName="Edit" OnClick="lbtnLInkButton_Click">"+<%#Eval("ticketNo")%> <%#Eval("subject")%> <%#Eval("qu")%>
</ItemTemplate>
</asp:repeater>
Bind This Repeater to Datatable or make Dummy DataTable and bind it.
DataTable dt = new DataTable();
dt.Columns.Add("ticketNo");
dt.Columns.Add("Subject");
dt.Columns.Add("qu");
for (int i = 0; i < list.Count; i++)
{
dt.Rows.Add(new object[] { "Ticket Number Value", "Subject Value", "qu Value"});
}
rpt.DataSource = dt;
rpt.DAtabind();
You can get button event like this
protected void lbtnLInkButton_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(((LinkButton)sender).CommandArgument);
}
***Note : I have writtern the code extempore and not rested it on Visual Studio so there May be Some Spelling Mistakes.**