Introduction
This article exposes, in a very simple and practical way, how a single RadioButton
acts as a RadioButtonList
in a web DataGrid
server control column. It�s nothing about two thousand lines of code, nor custom control, neither signed assembly. I always wonder why do complicated when we can do simple.
Solution
First, in the ItemCreated
DataGrid
event, I�ll wire the RadioButton
CheckedChanged
event:
private void DataGrid1_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
RadioButton oRb = ((RadioButton)e.Item.FindControl("rb"));
if(oRb != null)
{
oRb.CheckedChanged += new
System.EventHandler(this.rb_CheckedChanged);
}
}
Second, in the RadioButton
CheckedChanged
event, I�ll loop through DataGrid
items to find the previous and current radio buttons and, if found, the previously checked button will be unchecked:
private void rb_CheckedChanged(object sender, System.EventArgs e)
{
RadioButton oRb1 = (RadioButton)sender;
foreach(DataGridItem oItem in DataGrid1.Items)
{
RadioButton oRb2 = (RadioButton)oItem.FindControl("rb");
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);
}
else
oRb2.Checked = false;
}
}
The info is displayed in a message label after I�ve recuperated the lblId
and lblDesc
text from the HTML web form, like in the code below:
<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>
...
The DataGrid
is bound to an ArrayList
aList
in the BindDataGrid()
:
private void BindDataGrid()
{
ArrayList aList = new ArrayList();
for(int i=1; i<6; i++)
{
aList.Add(new ItemInfo(i, "Desc " + i.ToString()));
}
DataGrid1.DataSource = aList;
DataGrid1.DataBind();
}
For more details, please download the source code above. You have nothing else to do than to create a new C# project for an ASP.NET application and add the source code files. That�s all about it.
Enjoy!