Skip to content

Pre-selecting a datagrid Radio button using codebehind file.

david heath

Asked Apr 15, 2009, 12:47 AM EDT1 answer
Share
LinkedInX
Hi I hope you can help.

I have a web page with an ASP datagrid which populates address information. This also has a radio button to allow the user to select a row of the grid as their address.

<asp:DataGrid runat="server" ID="orgaddressdg" AutoGenerateColumns="false" >
<Columns>
<asp:BoundColumn DataField="AddressLine1" HeaderText="Address Line One"></asp:BoundColumn>
<asp:BoundColumn DataField="AddressLine2" HeaderText="Address Line Two"></asp:BoundColumn>
<asp:BoundColumn DataField="AddressLine3" HeaderText="Address Line Three"></asp:BoundColumn>
<asp:BoundColumn DataField="PostCode" HeaderText="Postcode"></asp:BoundColumn>
<asp:BoundColumn DataField="CountryName" HeaderText="Country"></asp:BoundColumn>
<asp:BoundColumn DataField="StatusDescription" HeaderText="Status"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Select One">
<ItemTemplate>
<input name="addr_radio_button" type="radio" value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Selecting a column works fine and I can get back the ID of the row. What I would like to do is on rendering of the datagrid, the user will already have an address ID so the corresponding row should be selected on render. How can I do this in the code behind file?

The address id will be an Int called selectedAddress. I have had a search and cant find anything that explains how this can be done. I realise I will need to go through each data grid row and check the ID value, but I am not sure how to do this. Any help would be great.

Thanks.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    I hope you can achieve this by placing bit of logic within the ItemDataBound event.

    Also you need to replace the html radio button with asp:RadioButton control.

    C#
    protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
    RadioButton rdAddressID = (RadioButton)e.Item.FindControl("RdButton");// "RdButton" is the ID of the radio button control
    string ID = e.Item.Cells[7].Text; //here cells[7] is the index of the Id column
    int SelectedAddressId = "Some Value";//Which is already available as mentioned by you
    if (rdAddressID != null)
    {
    if (SelectedAddressId == ID.ToString())
    {
    rdAddressID.Checked = true;
    }
    }
    }

    Hope this helps.

    0