IEVisual Studio .NET 2002.NET 1.0Visual Studio .NET 2003.NET 1.1HTML中级开发Visual StudioWindows.NETASP.NETC#
Web DataGrid 列中的简单 RadioButtonList
这是一种非常简单实用的方法,让单个 RadioButton 在 Web DataGrid 服务器控件列中充当 RadioButtonList。
引言
本文以非常简单实用的方式介绍了单个 RadioButton
如何在 Web DataGrid
服务器控件列中充当 RadioButtonList
。它没有两千行代码,也没有自定义控件,更没有签名程序集。我一直想知道,为什么我们要复杂化,而我们可以简单化呢?
解决方案
首先,在 ItemCreated
DataGrid
事件中,我将 RadioButton
CheckedChanged
事件绑定起来。
private void DataGrid1_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//Find the RadioButton control
RadioButton oRb = ((RadioButton)e.Item.FindControl("rb"));
if(oRb != null)
{
//Wire the RadioButton's event
oRb.CheckedChanged += new
System.EventHandler(this.rb_CheckedChanged);
}
}
其次,在 RadioButton
CheckedChanged
事件中,我将循环遍历 DataGrid
项目,以查找先前的和当前的单选按钮,如果找到,则取消选中先前选中的按钮。
private void rb_CheckedChanged(object sender, System.EventArgs e)
{
//Find the current selected RadioButton
RadioButton oRb1 = (RadioButton)sender;
foreach(DataGridItem oItem in DataGrid1.Items)
{
//Find the previous selected RadioButton
RadioButton oRb2 = (RadioButton)oItem.FindControl("rb");
//Display info for the current selected button
if( oRb2.Equals(oRb1) )
{
Message.Text =
String.Format("Selected Id is: {0},
and the Description is:{1}",
((Label)oItem.FindControl("lblId")).Text,
((Label)oItem.FindControl("lblDesc")).Text);
}
//Uncheck previously selected button
else
oRb2.Checked = false;
}
}
信息将在从 HTML Web 表单中恢复 lblId
和 lblDesc
文本后显示在一个消息标签中,如下面的代码所示。
<asp:label id="Message" Runat="server"></asp:label>
...
<Columns>
<asp:TemplateColumn HeaderText="Id">
<ItemTemplate>
<asp:Label id="lblId" runat="server" Text='<%#
DataBinder.Eval(Container.DataItem, "Id") %>' />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Description">
<ItemTemplate>
<asp:Label id="lblDesc" runat="server" Text='<%#
DataBinder.Eval(Container.DataItem,"Description") %>' />
</ItemTemplate>
</asp:TemplateColumn>
...
</Columns>
...
DataGrid
绑定到一个 ArrayList
aList
在 BindDataGrid()
中。
private void BindDataGrid()
{
ArrayList aList = new ArrayList();
for(int i=1; i<6; i++)
{
aList.Add(new ItemInfo(i, "Desc " + i.ToString()));
}
//Binding and displaying the info in the DataGrid
DataGrid1.DataSource = aList;
DataGrid1.DataBind();
}
有关更多详细信息,请下载上面的源代码。您所需要做的就是为 ASP.NET 应用程序创建一个新的 C# 项目,并添加源代码文件。就这样了。
尽情享用!