I have inherited an asp.net web app , that passes information to a gridview. Each row has different buttons and links on it and they 开发者_JS百科are enabled/disabled based on the information received. There is a very long chain of logic that each row goes through to set up the buttons, which makes it very difficult to read. Is there a way to set up a class of buttons to make this easier to read?
Not sure what you mean by a "class of buttons", but you can create a custom server controls as a wrapper to the button control, and provide some extra properties or methods to simplify the GridView logic.
Here's a quick and dirty example of a RadioButton wrapper that we built, which extends the properties of the standard Radio Button so it can hold extra information. You can try doing something similar for your GridView buttons:
[DefaultProperty("Text")]
[ToolboxData("<{0}:RadioButton runat=server></{0}:RadioButton>")]
public class RadioButton : System.Web.UI.WebControls.RadioButton
{
[Bindable(true)]
[DefaultValue("")]
[Localizable(true)]
public string Value
{
get
{
string RadioValue = (string)ViewState["Value"];
return (RadioValue == null) ? String.Empty : RadioValue;
}
set
{
ViewState["Value"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text);
}
}
One thing that you could do quickly would be to convert the DataSource to a report class. You could then move the logic for enabling/disabling into that class (i.e., individual property per button), and update the grid to simply check the appropriate property per link/button.
This at least moves the logic out of the aspx file to somewhere it can be maintained/perused more easily.
For example:
grid.DataSource = MyReportClass.GetReport();
Where
public MyReportClass
{
public string Name { get; set; }
public string EnableLink1 { get { //logic here } }
public string EnableButton3 { get { ///logic here } }
public static List<MyReportClass> GetReport()
{
// get the data
}
}
then the aspx becomes
<gridview id="grid" runat="server" ... >
...
<asp:templatefield headertext="Link1" ><itemtemplate>
<asp:linkbutton id="l1" runat="server" ...
visible='<%# !(bool)DataBinder.Eval(Container.DataItem, "EnableLink1") %>'
/>
</itemTemplate></asp:templatefield>
...
</gridview>
精彩评论