叫我“n00b”,但我是创建脚本控件的新手。我想创建一个带有 3 个文本框的简单控件。我有一个如下所示的 .cs 文件:
public class SmokingCalc : ScriptControl
{
public SmokingCalc()
{
Render(htmlWriter);
}
protected override void Render(HtmlTextWriter writer)
{
costTextbox.RenderControl(writer);
base.Render(writer);
}
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("SmokingCalc.SmokingCalc", this.ClientID);
yield return descriptor;
}
// Generate the script reference
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
yield return new ScriptReference("SmokingCalc.SmokingCalc.js", this.GetType().Assembly.FullName);
}
protected HtmlTextWriter htmlWriter;
protected TextBox costTextbox;
protected TextBox amountTextbox;
protected TextBox yearsTextbox;
protected Button submitButton;
}
}
我完全不知道为什么文本框不会呈现?我想我错过了一些东西......
[编辑] 我得到的错误是“对象引用未设置为对象的实例”。
[已回答] 我按如下方式更改了文件,并且至少到目前为止它可以工作。
public class SmokingCalc : ScriptControl
{
public SmokingCalc()
{
}
protected override void CreateChildControls()
{
base.CreateChildControls();
costTextbox.ID = "costTextbox";
amountTextbox.ID = "amountTextbox";
yearsTextbox.ID = "yearsTextbox";
submitButton.ID = "submitButton";
submitButton.Text = "Submit";
Controls.Add(costTextbox);
Controls.Add(amountTextbox);
Controls.Add(yearsTextbox);
Controls.Add(submitButton);
}
protected override IEnumerable<ScriptDescriptor>
GetScriptDescriptors()
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("SmokingCalc.SmokingCalc", this.ClientID);
descriptor.AddProperty("costTextboxID", costTextbox.ClientID);
descriptor.AddProperty("amountTextboxID", amountTextbox.ClientID);
descriptor.AddProperty("yearsTextboxID", amountTextbox.ClientID);
descriptor.AddProperty("submitButtonID", submitButton.ClientID);
yield return descriptor;
}
// Generate the script reference
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
yield return new ScriptReference("SmokingCalc.SmokingCalc.js", this.GetType().Assembly.FullName);
}
protected TextBox costTextbox = new TextBox();
protected TextBox amountTextbox = new TextBox();
protected TextBox yearsTextbox = new TextBox();
protected Button submitButton = new Button();
}