我想将对象列表绑定到gridview。该对象需要包含一列按钮。根据列表中的数据,需要禁用其中一些按钮。
是否可以生成包含启用或禁用按钮的对象列表并简单地绑定到gridview
?
您可以像这样添加按钮gridview
itemtemplate
:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" runat="server"
Text="click" Enabled="<%# Eval('IsButtonEnabled') %>"/>
</ItemTemplate>
</asp:TemplateField>
然后你可以在你的数据源中添加Flag
变量bool
并设置你想要的值,true
启用,false
禁用
编辑,例如你有这样的数据源:
class YourDataSource {
public string prop1 {get;set;}
public string prop2 {get;set;}
public bool IsButtonEnabled {get;set;}
}
如果IsButtonEnabled
为真,那么按钮将被启用,否则它将被禁用
拥有一个标志是一种好方法,但请记住,您需要以某种方式实际存储标志的状态并在每次数据更改时重新绑定它。我选择ViewState
了这个演示,这是完整的例子:
ASPX:
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Update" Enabled='<%# Eval("AllowUpdate") %>' OnClick="Update" CommandArgument='<%# Eval("Name") %>' />
<asp:Label runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后面的代码:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void BindData()
{
if (ViewState["Employees"] == null)
{
List<Employee> employees = new List<Employee>
{
new Employee{Name="Employee 1", AllowUpdate = true},
new Employee{Name="Employee 2", AllowUpdate = true}
};
gvEmployees.DataSource = employees;
ViewState["Employees"] = employees;
}
else
{
List<Employee> employees = ViewState["Employees"] as List<Employee>;
gvEmployees.DataSource = employees;
}
gvEmployees.DataBind();
}
protected void Update(object sender, EventArgs e)
{
Button update = sender as Button;
if (update != null & !String.IsNullOrEmpty(update.CommandArgument))
{
string employeeName = update.CommandArgument;
List<Employee> employees = ViewState["Employees"] as List<Employee>;
Employee emp = employees.Where(em => em.Name == employeeName).FirstOrDefault();
emp.Name = "some new value...";
emp.AllowUpdate = false;
//Rebind the grid with the new values
ViewState["Employees"] = employees;
BindData();
}
}
}
[Serializable]
public class Employee
{
public string Name { get; set; }
public bool AllowUpdate { get; set; }
}