我写了一个例子来创建ASP.NET Froms自己的控件。控件非常简单 - 组合框和按钮。用户需要选择值,当他提交按钮后,组合框中的值需要显示在标签中。 所以。我的控制代码:
public class MyControl:Control,IPostBackEventHandler
{
protected override void Render(HtmlTextWriter writer)
{
writer.AddAttribute("size","1");
writer.AddAttribute("ID","List2");
writer.AddAttribute("name", "ListYear");
writer.RenderBeginTag(HtmlTextWriterTag.Select);
for (int i = 1950; i < DateTime.Now.Year; i++)
{
writer.RenderBeginTag(HtmlTextWriterTag.Option);
writer.WriteEncodedText(i.ToString());
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.AddAttribute("type","submit");
writer.AddAttribute("value","ClickMe");
writer.AddAttribute("name","BtnChange");
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
base.Render(writer);
}
public delegate void OnClickEventHandler(object sender, EventArgs args);
public event OnClickEventHandler Click;
public void RaisePostBackEvent(string eventArgument)
{
Click(this, new EventArgs());
}
}
页面ASP:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestMyControl.aspx.cs" Inherits="Hello.TestMyControl" %>
<%@ Register assembly="Hello" namespace="Hello" tagPrefix="MyContrl" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
<MyContrl:MyControl runat="server" OnClick="Unnamed1_OnClick" ID="Control1"></MyContrl:MyControl>
</div>
</form>
</body>
</html>
最后的事件功能:
protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+Control1.????+" year";
}
从列表中获取值的问号可以替代什么?
P.S。奇怪的事情正在发生。因为当我单击按钮时,处理程序未被调用,我无法进入Unnamed1_OnClick
答案 0 :(得分:1)
由于您已在属性上设置了值,因此要检索它,您需要访问Attributes
属性
让您的控件继承自HtmlControl
public class MyControl : HtmlControl, IPostBackEventHandler
{
...
在您的页面上
<MyContrl:MyControl runat="server" OnClick="Unnamed1_OnClick" ID="Control1"></MyContrl:MyControl>
在你的代码上
Label1.Text = Control1.Attributes["value"];
您可以调试此行以查看所有可用属性
答案 1 :(得分:0)
您需要传递combobox
的名称及其所选文字的值。
像这样:
protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+ myCustomControl.SelectedItem.Value.ToString()
+ " year";
}
(抱歉。一旦我意识到自己的错误,我误读了最初的帖子并相应地编辑了我的代码。)
答案 2 :(得分:0)
将选择列表添加到名为=“YourSelectList”的用户控件
然后在click事件处理程序
中protected void Unnamed1_OnClick(object sender, EventArgs args)
{
Label1.Visible = true;
Label1.Text="You choose "+Control1.YourSelectList.SelectedValue.ToString()+" year";
}