Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding radiobuttonlist to datagrid and setting state

Status
Not open for further replies.

mit99mh

Programmer
Sep 24, 2002
246
GB
I recently had a request for editing data in a datagrid - the customer required the <EditTemplate> of the datagrid to contain a RadioButtonList set with data from a database.

I'd used texbox's a number of times in then <EditTemplate> of datagrids but never a radiobuttonlist - the following condenses a number of sites I visited before I got all the information I required including 4guysfromrolla but I couldn't find all the information in one place - I've put it all together and I hope it's helpful and if I've completely duplicated another post I do apologise.

.aspx page
Add a public method to get the data to populate the RadioButtonList control in the <EditItemTemplate>


<EditItemTemplate>
<asp:RadioButtonList ID="UserRolesRadio" datavaluefield="roleId" datatextfield="description" DataSource='<%# GetRoles() %>' Runat=server ><RadioButtonList>
</EditItemTemplate>


aspx.cs codebehind
GetRoles method plugs into a data store and returns data eg in a DataSet


/// <summary>
/// method to return all roles from database
/// </summary>
/// <returns></returns>
public DataSet GetRoles()
{
//create roles object
Roles AllRoles = new Roles( ConfigurationSettings.AppSettings["DbConnectionString"] );
//get and return all roles
return( AllRoles.GetRolesList());
}


This will populate the RadioButtonList in the datagrid but not set state.

To set state code has to be included in the PreRender event handler of the DataGrid.

Click on the DataGrid in the design view in VS.NET -> Click on the events icon ( lightning symbol ) and double click the PreRender event handler.
This opens up the event handler for this event in the code behind:

eg:

private void DataGrid1_PreRender(object sender, System.EventArgs e)
{
if (DataGrid1.EditItemIndex > -1)
{
RadioButtonList editUserRole = new RadioButtonList();
//find control and instantiate local web control
editUserRole = ( RadioButtonList )DataGrid1.Items[DataGrid1.EditItemIndex].FindControl( "UserRolesRadio" ) ;
//get userid primary key of row selected for edit
string userId = DataGrid1.DataKeys[ DataGrid1.EditItemIndex ].ToString();
//get current role for user from eg database
ArrayList roles = dataUser.GetUserRoles(userId);
//select appropriate listitem
editUserRole.Items.FindByText( roles[0].ToString() ).Selected = true;
}
}


State should be set on your radiobuttonlist - I 've not tried it out but you should be able to apply the same principle for dropdowns etc.





 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top