ViewState on programmatically loaded usercontrols (restored after Page_Load) - asp.net

I'm trying to create a simple web page with a navigation bar and some usercontrols (ascx) programmatically loaded.
All controls are inside an update panel.
When I click on a link button (from the navigation bar) I do the following things:
I save the current usercontrol using viewstate.
Than I reload the current usercontrol.
My 'page_load' always reloads the current control.
Always assigning the same ID to the programmatically loaded control allows me to save the usercontrol viewstate.
So everything look good except one little thing: the usercontrol viewstate in not available during the usercontrol Page_Load!
Look below for (* HERE).
The 'txtTest.Text' value is always "0" (also during postback).
It seems that the user control viewstate is restored after the (usercontrol) Page_Load.
How is it possible?
--- "DEFAULT.ASPX": ---
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<div class="links">
<asp:LinkButton ID="lnkButton1" runat="server" OnClick="lnkButton1_Click" Text="Link 1"></asp:LinkButton>
<asp:LinkButton ID="lnkButton2" runat="server" OnClick="lnkButton2_Click" Text="Link 2"></asp:LinkButton>
</div>
<br />
<asp:Panel ID="pnlCtrl" runat="server"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
--- "DEFAULT.ASPX.CS": ---
private string CtrlAscx
{
get
{
if (ViewState["CtrlAscx"] == null)
{
ViewState["CtrlAscx"] = String.Empty;
}
return ViewState["CtrlAscx"].ToString();
}
set
{
ViewState["CtrlAscx"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
loadMyControl();
}
private void loadMyControl()
{
if (!String.IsNullOrEmpty(CtrlAscx))
{
pnlCtrl.Controls.Clear();
Control c = LoadControl(CtrlAscx);
c.ID = CtrlAscx + "ID"; // this line is mandatory in order to mantain the usercontrol viewstate
pnlCtrl.Controls.Add(c);
}
}
protected void lnkButton1_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control1.ascx";
loadMyControl();
}
protected void lnkButton2_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control2.ascx";
loadMyControl();
}
-- "CONTROL1.ASCX" --
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Control1.ascx.cs" Inherits="WebTest.Control1" %>
Control1: <asp:TextBox id="txtTest" runat="server" Text="0"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" />
-- "CONTROL1.ASCX.CS" --
public partial class Control1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (txtTest.Text == "0") // * HERE
{
txtTest.Text = "1";
}
}
}

Try the EnableViewState="true" attribure on txtTest as well as on your custom user control when creating it :
.
.
c.EnableViewState = true;
pnlCtrl.Controls.Add(c);

Related

ASP.NET DropDownList SelectedIndexChanged event not working

I have a basic drop down list. Upon selection of an item in the list, I expect to update the label with the choice of drop down list. But my code section does not show any update. Here is the code:
MainPage.aspx.cs:
protected void Page_Load(Object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Use integers to index each item. Each item is a string.
Dictionary<int, string> fruit = new Dictionary<int, string>();
fruit.Add(1, "Kiwi");
fruit.Add(2, "Pear");
fruit.Add(3, "Mango");
fruit.Add(4, "Blueberry");
fruit.Add(5, "Apricot");
fruit.Add(6, "Banana");
fruit.Add(7, "Peach");
fruit.Add(8, "Plum");
// Define the binding for the list controls.
benimDropDownList.DataSource = fruit;
// Choose what you want to display in the list.
benimDropDownList.DataTextField = "Value";
// Activate the binding.
this.DataBind();
}
}
protected void benimDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
lblSonuc.Text = "You picked: " + benimDropDownList.SelectedItem.Text;
lblSonuc.Text += " which has the key: " + benimDropDownList.SelectedItem.Value;
}
MainPage.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="benimDropDownList" runat="server" OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged">
</asp:DropDownList>
<asp:Label ID="lblSonuc" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
What is wrong with it?
Add AutoPostBack="true" to the <asp:DropDownList>:
<asp:DropDownList ID="benimDropDownList" runat="server"
OnSelectedIndexChanged="benimDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
By default <asp:DropDownList> do not post back changes to the server.
You might also want to set the DataValueField for your dropdownlist:
benimDropDownList.DataValueField = "Key";

Button not fired up inside asp user control used for umbraco macro

I'm searching solutions for my problem already since 2-3h and I decided better to ask.
I have created and empty web site and the installed umbraco, set up a new macro and it seemd ok but a button is not fired .
The code in Test.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Tests.ascx.cs" Inherits="Demo.Tests" %>
<h1>test</h1>
<form id="Form1" runat="Server">
<asp:Button ID="btnRunTest" OnClick="onClick_btnRunTest" Text="Run test" runat="server" CausesValidation = "false"/>
</form>
<div style="background-color: #de6363; padding: 10px;">
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor="black" />
</div>
And code behind:
public partial class Tests : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//btnRunTest.Click += new EventHandler(this.onClick_btnRunTest);
}
public void onClick_btnRunTest(object sender, EventArgs e)
{
lblMessage.Text = "";
Stopwatch stopwatch = Stopwatch.StartNew();
DynSLinkedList<int?> list = new DynSLinkedList<int?>();
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Remove(18);
list.Remove(-2);
list.Remove(1);
var time = stopwatch.Elapsed.ToString();
lblMessage.Text = "Task finished in time "+time +"</br>";
}
}
When I hit the button page reloads but the onClick_btnRunTest is not hit

asp.net: ListView on the masterpage

I have some asp.net pages.
I used the masterpage to implement common control.
There is a listview on the masterpage.
And there is a label on the contentpage.
I want to implement below.
When user select a node on the listview of masterpage,
the label text on the contentpage is changed into the text of the node.
How can i implement this.
Could you give me some advice or some link about my question?
Thank you in advance.
On Master1.master, I used ItemCommand event on ListView
<form id="form1" runat="server">
<asp:ListView ID="List1" runat="server" onitemcommand="List1_ItemCommand">
<ItemTemplate>
<p>
<asp:label ID="ItemLabel" runat="server" text="<%#Container.DataItemIndex %>" />
<asp:LinkButton ID="ItemLink" runat="server" CommandName="SelectItem" Text="Select" />
</p>
</ItemTemplate>
</asp:ListView>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</form>
And Master1.master.cs, store selected item text to public property
public partial class Master1 : System.Web.UI.MasterPage
{
public string selectedText { get; set; }
protected void List1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "SelectItem")
{
selectedText = ((Label)e.Item.FindControl("ItemLabel")).Text;
}
}
}
Then in Content1.aspx , add a label with id Label1
<asp:Label ID="Label1" runat="server" />
Finally in Conetnt1.aspx.cs, read the property "selectedText" on prerender event (which comes after select click)
protected void Page_PreRender(object sender, EventArgs e)
{
var myMaster = (Master1)this.Master;
Label1.Text = myMaster.selectedText;
}

Cannot update the data in ASPxGridControl

I found that I cannot update the data in my second grid when I clicked on the first grid control.
There are two grids in my program and there is overloaded function GetDataTable2() to get DataTable according to the focused row in grid1.
However, I dun know why the grid2 cannot be updated.
Please help!
protected void Page_Load(object sender, EventArgs e)
{
gv1.DataSource = GetDataTable1();
gv1.KeyFieldName = "ID";
gv1.DataBind();
gv2.DataSource = GetDataTable2();
gv2.DataBind();
}
protected void gv1_FocusedRowChanged(object sender, EventArgs e)
{
gv2.DataSource = GetDataTable2((int)gv1.GetRowValues(gv1.FocusedRowIndex, "ID"));
gv2.DataBind();
}
And the asp.net:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<dx:ASPxGridView ID="gv1" runat="server" SettingsBehavior-AllowFocusedRow="true" SettingsBehavior-ProcessFocusedRowChangedOnServer="true" OnFocusedRowChanged="gv1_FocusedRowChanged" >
</div>
<div>
<dx:ASPxGridView ID="gv2" runat="server" >
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
I think that if you set the ASPxGridView's EnableCallbacks property to false, your code will start working properly. This is the recommended way of using ASPxGridView when it is located within the MS UpdatePanel.
You don't need the UpdatePanel.
In the first grid, use the "RowClick" client side event and perform a callback in the second grid.
ClientSide Event
function gv1_RowClick(s, e) {
gv2.PerformCallback("UPDATE_SECOND_GRID|" + gv1.GetRowKey(e.visibleIndex));
}
ServerSide Event
protected void gv2_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
{
string[] args = e.Parameters.Split('|');
if (args == null || args.Length == 0)
return;
if (args[0].Equals("UPDATE_SECOND_GRID")) {
//your code with args[1] (key of the first grid)
gv2.DataSource = GetDataTable2();
gv2.DataBind();
}
}

Best way to display Dynamic Content (From Database) in ASP.NET Web Page

I want to display my database table's one row content like as below frame. Table have Photo and description column. I also want two buttons like mentioned in image for some action. my database table have around 100 plus records. so in my web page I want to display 100 frame like below at runtime because it's possible that in future this record may goes up to 1000.
I am new in Web Application development. Anyone suggest me best GUI control to achive my goal with ASP.NET. Any tutorial or sample link will be great help.
Thanks.
First you create a user control with that design as I see here.
Then you use this user control inside a repeater and pass the database parameters to the user control to make the correct render. Additional you can use and DataView the same way.
working example
The custom control:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ShowData.ascx.cs" Inherits="Dokimes_StackOverFlow_ShowData" %>
<asp:Literal runat="server" ID="txtTheID" EnableViewState="false" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<hr /><br />
and the code behind:
public partial class Dokimes_StackOverFlow_ShowData : System.Web.UI.UserControl
{
public int cValueID = -1;
protected void Page_Load(object sender, EventArgs e)
{
txtTheID.Text = cValueID.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
and the main page that is use it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<uc1:ShowData ID="ShowData1" runat="server" cValueID="<%# GetID(Container.DataItem) %>" />
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
and the code behind
public partial class Dokimes_StackOverFlow_ShowRepeatedData : System.Web.UI.Page
{
List<int> oMainIds = new List<int>();
override protected void OnInit(EventArgs e)
{
for (int i = 0; i < 10; i++)
{
oMainIds.Add(i);
}
Repeater1.DataSource = oMainIds;
Repeater1.DataBind();
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public int GetID(object oItem)
{
return (int)oItem;
}
}
You can use listview control because it supports custom formatting. repeater is the second option but listview has more features than repeater.

Resources