473,692 Members | 2,236 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Updating property value in a custom contorl using ASP.NET 2.0 Callback

Hello All,

I'm a new ASP.NET programmer and I want to create a custom control
consist of two properties (Number1) and (Number2) and both of them are
integers and default value = 0,

now I'm using callback technique so I can change those two proprties
via ChangeNumber1 and ChangeNumber2 functions.

what happens is that when I change the Number1 for to number and get
the result of the callback event and trying to change the second number
I always get the default value of Number1 (which is 0) and always the
result return 0;

I know that I can pass the two new properties value via the callback
function but I want it works like this.

anybody can help ?

=============== =============== =============== =============== ============
My Custom Contorl code is:
[ToolboxData("<{ 0}:MyCalculator runat=server></{0}:MyCalculato r>")]
public class MyCalculator : WebControl, ICallbackEventH andler
{
private const int _number1Default = 0;
private const string _number1Default ViewState = "Number1";

[Bindable(true)]
[DefaultValue(_n umber1Default)]
[Description("Th e first number")]
[Localizable(tru e)]
public int Number1
{
get
{
object obj = ViewState[_number1Default ViewState];
return (obj != null) ? (int)obj : 0;
}
set
{
ViewState[_number1Default ViewState] = value;
}
}

private const int _number2Default = 0;
private const string _number2Default ViewState = "Number2";

[Bindable(true)]
[DefaultValue(_n umber2Default)]
[Description("Th e first number")]
[Localizable(tru e)]
public int Number2
{
get
{
object obj = ViewState[_number2Default ViewState];
return (obj != null) ? (int)obj : 0;
}
set
{
ViewState[_number2Default ViewState] = value;
}
}

protected override void OnPreRender(Eve ntArgs e)
{
ClientScriptMan ager csm = this.Page.Clien tScript;

{ // Number1 Script Register
String cbNumber1Ref = csm.GetCallback EventReference( this,
"eventArgument" ,
"GetMultiplyRes ult", "context");

StringBuilder sbNumber1Callba ckScript = new
StringBuilder() ;
sbNumber1Callba ckScript.Append ("\n");
sbNumber1Callba ckScript.Append ("function
ChangeNumber1(e ventArgument, context)\n");
sbNumber1Callba ckScript.Append ("{\n");
sbNumber1Callba ckScript.Append (" " + cbNumber1Ref);
sbNumber1Callba ckScript.Append (";\n}");

// Register script blocks will perform call to the server.
if (!csm.IsClientS criptBlockRegis tered(this.GetT ype(),
"OnChangeNumber 1"))
{
csm.RegisterCli entScriptBlock( this.GetType(),
"OnChangeNumber 1",
sbNumber1Callba ckScript.ToStri ng(), true);
}
}

{ // Number2 Script Register
String cbNumber2Ref = csm.GetCallback EventReference( this,
"eventArgument" ,
"GetMultiplyRes ult", "context");

StringBuilder sbNumber2Callba ckScript = new
StringBuilder() ;
sbNumber2Callba ckScript.Append ("\n");
sbNumber2Callba ckScript.Append ("function
ChangeNumber2(e ventArgument, context)\n");
sbNumber2Callba ckScript.Append ("{\n");
sbNumber2Callba ckScript.Append (" " + cbNumber2Ref);
sbNumber2Callba ckScript.Append (";\n}");

// Register script blocks will perform call to the server.
if (!csm.IsClientS criptBlockRegis tered(this.GetT ype(),
"OnChangeNumber 2"))
{
csm.RegisterCli entScriptBlock( this.GetType(),
"OnChangeNumber 2",
sbNumber2Callba ckScript.ToStri ng(), true);
}
}
}
public override void RenderControl(H tmlTextWriter writer)
{
writer.RenderBe ginTag(HtmlText WriterTag.B);
writer.Write("T his is My Control");
writer.RenderEn dTag();
}

private int _result;
void ICallbackEventH andler.RaiseCal lbackEvent(stri ng
eventArgument)
{
string[] args = eventArgument.S plit(':');

switch (args[0])
{
case "Number1":
{
Number1 = int.Parse(args[1]);
}
break;

case "Number2":
{
Number2 = int.Parse(args[1]);
}
break;
}

_result = Number1 * Number2;
}

string ICallbackEventH andler.GetCallb ackResult()
{
return _result.ToStrin g();
}
}
=============== =============== =============== =============== ============

And the page that uses it is:
=============== =============== =============== =============== ============
<%@ Page Language="C#" AutoEventWireup ="true"
CodeFile="Defau lt.aspx.cs" Inherits="_Defa ult" %>

<%@ Register Assembly="WebCo ntrolLibrary1"
Namespace="WebC ontrolLibrary1" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
<script type="text/javascript">
function OnChangeNum1()
{
var cmb1 = document.getEle mentById("Selec t1");
ChangeNumber1(c mb1.selectedInd ex);
}

function OnChangeNum2()
{
var cmb2 = document.getEle mentById("Selec t2");
ChangeNumber2(c mb2.selectedInd ex);
}

function GetMultiplyResu lt(mulResult)
{
document.getEle mentById("Text1 ").value = mulResult;
}
</script>
<script src="ClientScri pt.js" type="text/javascript">
// <!CDATA[

// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<strong>First Number &nbsp; &nbsp; :</strong> &nbsp;
<select id="Select1" onchange="OnCha ngeNum1()" style="width:
121px" onclick="return Select1_onclick ()">
<option selected="selec ted">0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br />
<strong>Secon d Number:</strong> &nbsp;&nbsp;<se lect id="Select2"
onchange="OnCha ngeNum2()" style="width: 121px">
<option selected="selec ted">0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br />
<br />
<strong>Result: </strong>
<input id="Text1" type="text" style="width: 170px" /><br />
<br />
&nbsp;<cc1:MyCa lculator ID="MyCalculato r1" runat="server"
Width="257px" />
</div>
</form>
</body>
</html>
=============== =============== =============== =============== ============

Thanks
Omar alani

Jan 19 '06 #1
2 2508
Try saving the values to Session state instead of ViewState.
You see, ViewState is not being persisted because it normally gets rendered
along with the page but in the case of callbacks you are not re-rendering the
page.

--
I hope this helps,
Steve C. Orr
MCSD, MVP
http://Steve.Orr.net

"Alani" wrote:
Hello All,

I'm a new ASP.NET programmer and I want to create a custom control
consist of two properties (Number1) and (Number2) and both of them are
integers and default value = 0,

now I'm using callback technique so I can change those two proprties
via ChangeNumber1 and ChangeNumber2 functions.

what happens is that when I change the Number1 for to number and get
the result of the callback event and trying to change the second number
I always get the default value of Number1 (which is 0) and always the
result return 0;

I know that I can pass the two new properties value via the callback
function but I want it works like this.

anybody can help ?

=============== =============== =============== =============== ============
My Custom Contorl code is:
[ToolboxData("<{ 0}:MyCalculator runat=server></{0}:MyCalculato r>")]
public class MyCalculator : WebControl, ICallbackEventH andler
{
private const int _number1Default = 0;
private const string _number1Default ViewState = "Number1";

[Bindable(true)]
[DefaultValue(_n umber1Default)]
[Description("Th e first number")]
[Localizable(tru e)]
public int Number1
{
get
{
object obj = ViewState[_number1Default ViewState];
return (obj != null) ? (int)obj : 0;
}
set
{
ViewState[_number1Default ViewState] = value;
}
}

private const int _number2Default = 0;
private const string _number2Default ViewState = "Number2";

[Bindable(true)]
[DefaultValue(_n umber2Default)]
[Description("Th e first number")]
[Localizable(tru e)]
public int Number2
{
get
{
object obj = ViewState[_number2Default ViewState];
return (obj != null) ? (int)obj : 0;
}
set
{
ViewState[_number2Default ViewState] = value;
}
}

protected override void OnPreRender(Eve ntArgs e)
{
ClientScriptMan ager csm = this.Page.Clien tScript;

{ // Number1 Script Register
String cbNumber1Ref = csm.GetCallback EventReference( this,
"eventArgument" ,
"GetMultiplyRes ult", "context");

StringBuilder sbNumber1Callba ckScript = new
StringBuilder() ;
sbNumber1Callba ckScript.Append ("\n");
sbNumber1Callba ckScript.Append ("function
ChangeNumber1(e ventArgument, context)\n");
sbNumber1Callba ckScript.Append ("{\n");
sbNumber1Callba ckScript.Append (" " + cbNumber1Ref);
sbNumber1Callba ckScript.Append (";\n}");

// Register script blocks will perform call to the server.
if (!csm.IsClientS criptBlockRegis tered(this.GetT ype(),
"OnChangeNumber 1"))
{
csm.RegisterCli entScriptBlock( this.GetType(),
"OnChangeNumber 1",
sbNumber1Callba ckScript.ToStri ng(), true);
}
}

{ // Number2 Script Register
String cbNumber2Ref = csm.GetCallback EventReference( this,
"eventArgument" ,
"GetMultiplyRes ult", "context");

StringBuilder sbNumber2Callba ckScript = new
StringBuilder() ;
sbNumber2Callba ckScript.Append ("\n");
sbNumber2Callba ckScript.Append ("function
ChangeNumber2(e ventArgument, context)\n");
sbNumber2Callba ckScript.Append ("{\n");
sbNumber2Callba ckScript.Append (" " + cbNumber2Ref);
sbNumber2Callba ckScript.Append (";\n}");

// Register script blocks will perform call to the server.
if (!csm.IsClientS criptBlockRegis tered(this.GetT ype(),
"OnChangeNumber 2"))
{
csm.RegisterCli entScriptBlock( this.GetType(),
"OnChangeNumber 2",
sbNumber2Callba ckScript.ToStri ng(), true);
}
}
}
public override void RenderControl(H tmlTextWriter writer)
{
writer.RenderBe ginTag(HtmlText WriterTag.B);
writer.Write("T his is My Control");
writer.RenderEn dTag();
}

private int _result;
void ICallbackEventH andler.RaiseCal lbackEvent(stri ng
eventArgument)
{
string[] args = eventArgument.S plit(':');

switch (args[0])
{
case "Number1":
{
Number1 = int.Parse(args[1]);
}
break;

case "Number2":
{
Number2 = int.Parse(args[1]);
}
break;
}

_result = Number1 * Number2;
}

string ICallbackEventH andler.GetCallb ackResult()
{
return _result.ToStrin g();
}
}
=============== =============== =============== =============== ============

And the page that uses it is:
=============== =============== =============== =============== ============
<%@ Page Language="C#" AutoEventWireup ="true"
CodeFile="Defau lt.aspx.cs" Inherits="_Defa ult" %>

<%@ Register Assembly="WebCo ntrolLibrary1"
Namespace="WebC ontrolLibrary1" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitl ed Page</title>
<script type="text/javascript">
function OnChangeNum1()
{
var cmb1 = document.getEle mentById("Selec t1");
ChangeNumber1(c mb1.selectedInd ex);
}

function OnChangeNum2()
{
var cmb2 = document.getEle mentById("Selec t2");
ChangeNumber2(c mb2.selectedInd ex);
}

function GetMultiplyResu lt(mulResult)
{
document.getEle mentById("Text1 ").value = mulResult;
}
</script>
<script src="ClientScri pt.js" type="text/javascript">
// <!CDATA[

// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<strong>First Number :</strong>
<select id="Select1" onchange="OnCha ngeNum1()" style="width:
121px" onclick="return Select1_onclick ()">
<option selected="selec ted">0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br />
<strong>Secon d Number:</strong> <select id="Select2"
onchange="OnCha ngeNum2()" style="width: 121px">
<option selected="selec ted">0</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select><br />
<br />
<strong>Result: </strong>
<input id="Text1" type="text" style="width: 170px" /><br />
<br />
<cc1:MyCalculat or ID="MyCalculato r1" runat="server"
Width="257px" />
</div>
</form>
</body>
</html>
=============== =============== =============== =============== ============

Thanks
Omar alani

Jan 19 '06 #2
Thank you Steve for your reply.

your suggesstion worked correctly, BUT when I changed the class
declaration to add some initial value for the Number1 and Number2
properties, I got an exception because the Page.Session variable was
null in the set section of the property, I mean if I changed the class
declaration to be as follows:
=============== =============== =============== =============== =============== ==========
[ToolboxData("<{ 0}:MyCalculator runat=server Number1=0
Number2=0></{0}:MyCalculato r>")]

and change the property to be as follows:

[Bindable(true)]
[DefaultValue(_n umber1Default)]
[Description("Th e first number")]
[Localizable(tru e)]
public int Number1
{
get
{
object obj = null;
if (Page.Session != null)
{
//get a property unique name by adding the clientId for
this control to the original property name
string Number1ID = string.Format(" {0}_Number1",
this.ClientID);
obj = Page.Session[Number1ID];
}
return (obj != null) ? (int)obj : 0;
}
set
{
if (Page.Session != null)
{
string Number1ID = string.Format(" {0}_Number1",
this.ClientID);
Page.Session[Number1ID] = value;
}
}
}

=============== =============== =============== =============== =============== ==========

Now, Is this what you mean or you meant something else ?

Is my code right or wrong ?

Thanks again,
Omar alani

Jan 22 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3405
by: Jim Hammond | last post by:
It would be udeful to be able to get the current on-screen values from a FormView that is databound to an ObjectDataSource by using a callback instead of a postback. For example: public void RaiseCallbackEvent(string eventArgs) { // update the data object with the values currently on screen FormView1.UpdateItem(true); }
15
1909
by: Sam Kong | last post by:
Hello! I got recently intrigued with JavaScript's prototype-based object-orientation. However, I still don't understand the mechanism clearly. What's the difference between the following two? (1)
5
2758
by: Mark Ingram | last post by:
Hi, ive written a custom control and i would like to display the "invalid property value" dialog box for certain properties on my form if the user enters a value outside the allowed range (in the visual studio designer). e.g. If i had a percentage property, i would want the user only to be able to enter Int32 values between 0&100. How can i do this?
0
1227
by: yp.yean | last post by:
Hi, I created a custom control, and encountered a dirty property value persistence problem. I created a property with a custom class type, call SQLSettings which holds the SQL connection parameters, the class as follows: public sealed class SQLSettings { private string serverName;
1
1057
by: shapper | last post by:
Hello, I am creating a custom control and I have the following property: <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)Property Text() As String Get Dim s As String = CStr(ViewState("Text")) If s Is Nothing Then Return String.Empty Else
4
1341
by: Nemisis | last post by:
Hi everyone, I am wondering if anyone has tried the following saving values from a page to a database using CallBack? is this possible? Basically instead of pressing a button that contacts the server and refreshes the whole page, i was wondering if it is possible to allow the user to update certain values within textboxs and dropdownlist, and then obtain the values entered on a callback.
5
1519
by: TS | last post by:
I have a custom textbox that i need to access a label's text property. the label and textbox are 2 separate controls that will be on my page. Inside my custom control i want to have access to this label's text. I was thinking of having a property on my textbox that was something like LabelControlID. the textbox could then do a .Findcontrol on its parent control to find this label and access its text. i thought that this might be an...
0
1748
by: balajipkn | last post by:
Hi, I am trying to pass parameters from WIX to C# code, but I am not able to do it properly. To code that I have written on WIX side is: <Property Id="teststring"> <!]> </Property> <CustomAction Id="testing" Return="check" BinaryKey="test" DllEntry="hello"/> <Binary Id="test" src="test.dll" /> <CustomAction Id="testing.setproperty" Return="check" Property="testing" Value="" />
2
1835
by: Fabio Mastria | last post by:
Hi all! In a my simple project I use callback to fill a dropdownlist with xml data returned by a web service, based on a value which is input via another dropdownlist. NOTE: I can't use ajax/atlas. Using javascript and callback all works... but if I press a button or any event that raise a postback, the dropdownlist that I fill gets empty!
0
8538
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9083
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8961
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8801
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5819
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4324
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2974
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2238
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1957
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.