How to replace an entire ASP control - c#

I want to display a lot of data in a Table control, but put the code in a library method that returns a new Table object. When I assign that object directly to the control on the ASP page, the data does not show.
The library method looks like this:
public Table CreateTable(...)
{
Table tbl = new Table();
...
// adding lots of cells and setting lots of properties
...
return tbl;
}
The ASP page has a Table control:
<asp:Content ID= ... >
<asp:Table ID="Table_Data" runat="server">
</asp:Table>
</asp:Content>
In Code-Behind the Table control is assigned the new Table object:
protected void Button_Click(object sender, EventArgs e)
{
Table_Data = Lib.CreateTable(...);
}
but when tested the Table control shows empty.
This principle has worked by this:
Table NewTable = Lib.CreateTable(...);
PlaceHolder1.Controls.Add(NewTable);
but it seems that having a PlaceHolder in my asp page should not be needed.
Or is it?
Any help is appreciated!
Update:
The solution is, as the Accepted Answer, to keep the PlaceHolder, but not <asp:Content> but a new PlaceHolder control at the exact place where I want the table:
<asp:PlaceHolder ID="PlaceHolder_Table" runat="server">
</asp:PlaceHolder>
and in Code Behind:
PlaceHolder_Table.Controls.Add(Lib.CreateTable(...));
Simple, and works great.

<asp:Content ID="contId" >
<asp:Table ID="Table_Data" runat="server">
</asp:Table>
</asp:Content>
protected void Button_Click(object sender, EventArgs e)
{
contId.Controls.Clear();
contId.Controls.Add(Lib.CreateTable(...));
}

The asp.net table control isn't supposed to work like this. You're most likely looking for the GridView control, see here. This is used for getting data, binding it to the Gridview and displaying it
The asp.net table control info is here. It's more of a format thing rather than using for loads of data, that's why you can't databind to it.

Related

Convert HTML table code to asp:table control

I have an HTML table code (starts with <table> and ends with </table>), how can I make my asp web page to add this table programmatically?
If you have purely HTML code generated in server side, then you can add that HTML code having <Table> into your asp page like this.
Add a placeholder to aspx page like this.
<asp:PlaceHolder ID="plc" runat="server" />
In page_load event write this.
String str = "<table><tr><td>TD VALUE</td></tr></table>";
plc.Controls.Add(new LiteralControl(str));
This will emit html code , and place them to placeholder.
ASSUMPTION This is just a readonly html code , that you wan to show in page, you are not intended to get those value in server side code on post back. Nor there is any editable field inside the generated table.
if you want to access this table programatically then use
<table runat="server" id="YOUR_ID"></TABLE>
it will then let you access this control through asp.net
Either redo it in asp:table as you already mentioned or add runat="server" to your existing table and you will be able to alter it in codebehind.
After runat = server you can do things like
protected void Page_Load(object sender, EventArgs e)
{
var str= tbl1.Rows[0].Cells[2].InnerHtml;
}
But I would probably redo it in <asp:table> if you are using webforms. See full example here
Add rows to a table dynamically

ASP.NET/C# trying to use page_load method on a form with #A on end of web address through link

I am needing to use the same form for displaying multiple things and I realize that when I add links like:
A
it has the same form and web address, but with a #A at the end of the address.I thought I could use this for displaying multiple things on the same form. My idea is to have C# code in the page_load method to detect what the web address is and use a conatins method for the url string and detect if there is #A to change the content of the form. Here is an example:
C# code:
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("#A"))
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
asp.net code:
A
<div ID="div1" runat="server">
content 1
</div>
<div ID="div2" runat="server">
content 2
</div>
I have tried to put the Page_Load method in a script tag, but still didn't work. I guess since the url is different the cs code is not valid? I know it goes through the page_load method once, before I click on the link. Also I do use a method that gives me the controls of div1 and div2, so that is not the problem. I thank everyone in advance for your help! Also if my way is not the way to do the job then please tell me any way possible to achieve what I am trying to do.
edit: I can't use a button to replace a link... maybe a asp:hyperlink?
That's an HTML hyperlink you're using and it won't cause a postback thus page_load will never get called when you click it.
I would suggest if you want to show an hide divs that you use client side JavaScript. Alternatively you could (for example) use an asp.net button control which will cause a postback.
I would suggest scrapping the anchor with an href approach in favor of this:
Use the ASP.NET server controls, along with their click event handlers to manage the visibility of controls on your page.
In your Page_Load, make it so the page has an initial state of showing controls, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
div1.Visible = false; //content 1
div2.visible = true; //content 2
}
}
Now instead of an anchor tag, you can use an ASP.NET Button or LinkButton to cause a postback to the server, like this:
<asp:Button id="Button1"
Text="Click here to change page to B"
OnClick="Button1_Click"
runat="server"/>
Now you have the event handler code which would change the visibility of controls, like this:
protected void Button1_Click(Object sender, EventArgs e)
{
div1.Visible = true; //content 1
div2.visible = false; //content 2
}

ASP.NET Expression: Accessing the Property of a Class

Is there any way to directly access a field of class in the aspx page?
I have tried this:
In the aspx page I have added:
<form id="LoginForm" runat="server">
<asp:Label Text='<%# Eval("Test") %>' runat="server" ID="jym" />
</form>
and in the backend class of this page I have declared a property as:
private string test;
public string Test {
get {
return test;
}
set {
test = value;
}
}
This property is initialized in Page_Load() as: Test = "JYM";
But the problem is I am unable to see this value in the browser. The tag is rendered into <span/> but without any content.
What I am doing wrong?
Are you calling Page.DataBind() in Page_Load()?
You are using the # data binding operator in your embedded code block. The values that you bind to the control will only show after you have called DataBind() from either the control or the page (which will in turn call it for each control on the page).
If you only want to bind a value to that single label control you could just call jym.DataBind().
I would however suggest using a more descriptive name (id) for the Label control so it is clearer in the code about what is being databound.
See this page for more details.
UPDATE (extra info requested by OP in comment)
So you have 3 options:
1.
Call DataBind() as suggested above.
2.
Don't use a server side control for the label. Just use plain HTML and then you can use the following syntax:
<p><%= Test %></p>
3.
Set the value of the label in the code behind. For example in your page load you might have the following:
protected void Page_Load(object sender, EventArgs e)
{
jym.Text = Test;
}
You may want to use <%= this.Test%>. You can also do this.jym.Text=Test; in the Page Load evt.

How do I add controls dynamically to a dynamically created panel?

I have a repeater that creates n-number of panels. I am trying to dynamically add different controls to each of the panels. I may very well be going about this the wrong way.
My code is more or less:
.aspx:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<% Response.Write("<asp:panel runat=\"server\" id=\"uxPanel_"); %>
<%# DataBinder.Eval(Container.DataItem, "TableId")%><% Response.Write("\"></asp:panel>"); %>
</ItemTemplate>
</asp:Repeater>
.cs:
public partial class class1: System.Web.UI.Page
{
DataSet ds= null;
protected void Page_Load(object sender, EventArgs e)
{
GetRecords(1,1);
}
protected void GetRecords()
{
ds= dal.LoadRecords();
this.Repeater1.DataSource = ds.Tables[0];
this.Repeater1.DataBind();
Literal lit = new Literal();
lit.Text = "Some text";
this.FindControl("uxPanel_1").Controls.Add(lit);
}
}
Just to be clear in this example "dal.LoadRecords" is simply call to a method that retrieves some records from a DB.
I think my problem is how I am adding my panels in the first place, but this seemed like an easy way to have them uniquely named.
Any Pointers?
Thanks
As the previous answerer has said, this is fraught with peril!
If you must: I should ditch the repeater approach altogether.
Create a container panel or placeholder and in the code behind dynamically add your panels to that using ContainerPanel.Controls.Add(newPanel);
Your child "panel" could be a UserControl if needs be too.
Be aware that you'll have to regenerate your dynamic controls on postback.
Pointers? Yes : Don't dynamically add controls!
Dynamically adding controls adds a lot of overhead and you run into issues with viewstates. Usually , it's not worth the time and headaches.
Panels, as well as Literals, PlaceHolders, and every other ASP.NET control have a Visible property that you can toggle on and off, like so:
myPanel.Visible=true;
myOtherPanel.Visible = false;
myTogglePanel.Visible = ! myTogglePanel.Visible; //toggle it's visibility
This approach is much, much easier.

How to display elements only if SQLDataSource has rows

I'm creating an ASP.NET/C# page where a user enters an ID at the top of the page, and when they press Submit, the page posts back and displays the data. Right now, the data fields are displayed at all times - even when the page loads and no search has taken place. This is not ideal as when they navigate a Menu with a MultiView I have made, some errors will come up. Plus it's obviously not good practise.
Is there a way I can hide all these elements (they are DetailsViews and GridViews, plus the MultiView and Menu) if the SQLDataSource is blank? So if the search returned nor esults, or no query has been executed yet.
Thanks
You could surround these elements is a placeholder control and then set the placeholders visibility depending on whether there are result to display.
I haven't used the SqlDataSource object much before but to meet you requirements I would suggest checking to see if the page has been posted back in the PageLoad method and if not hiding the data controls. Then to handle the case of no results being returned adding a method to the SqlDataSource.Selected event:
ASPX:
<asp:PlaceHolder ID="myPlaceholder" runat="server">
....Data controlds
</asp:PlaceHolder>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack)
{
myPlaceholder.Visible = false;
}
}
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
myPlaceholder.Visible = e.AffectedRows > 0;
}
If GridView1.Rows.Count > 0 // then do stuff
DataView dv = (DataView)SqlDSourse.Select(DataSourceSelectArguments.Empty);
if(dv.count>0)
{
...
}

Categories

Resources