I have an ASP.NET webforms site that is used mainly for managing data. One of the tables basically has name/value (string/string) data (no type information, just strings).
I want to make a page that can dynamically load up a table of controls for each record (with a label for the name, 开发者_开发问答and either a TextBoxes for a string/nubmer, or a CheckBoxes for a value that is "true" or "false" - I'll assume it's boolean.)
Are there any built-in controls that can easily do this? If not - if I wanted to just dynamically load Labels and TextBoxes/CheckBoxes into a collection to display, what would be a good Control to use for the collection (e.g. DataGrid, Repeater, etc.)
Check out the property grid: http://propertygrid.codeplex.com/
It is a 3rd party (albiet free/open source), however it is quite handy for name/value type stuff.
I prefer using the standard ASP.Net ListView control, mostly because it is not much more complex than a Repeater control, but the ListView can support data paging. If you need to be able to sort your results by column, however, you may want to look at the GridView control.
You can build up the list dynamically with something like this. If the value looks like a bool using TryParse it renders a CheckBox, otherwise it puts the value in a TextBox.
foreach (var item in data)
{
var controls = ListPlaceholder.Controls;
// Add the label
var label = item.Key;
controls.Add(new LiteralControl(label));
var value = item.Value.ToString();
bool boolVal;
if (bool.TryParse(value, out boolVal))
{
// Looks like a bool so render CheckBox
controls.Add(new CheckBox { Checked = boolVal });
}
else
{
// General data so render TextBox
controls.Add(new TextBox { Text = value });
}
// Line break
controls.Add(new LiteralControl("<br />"));
}
Try the DataList control. It gives you a lot of flexibility in formatting. you could also write a user control if you see it being used everywhere. In fact your DataList can be inside a user control if re-usability is important.
精彩评论