将列表绑定到gridview,包括按钮

时间:2013-01-14 14:53:10

标签: c# asp.net gridview

我想将一个对象列表绑定到gridview。该对象需要包含一列按钮。根据列表中的数据,需要禁用其中一些按钮。

是否可以生成对象列表,包括启用或禁用按钮,只需绑定到gridview

2 个答案:

答案 0 :(得分:1)

您可以在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为真,那么按钮将被启用,否则将被禁用

答案 1 :(得分:1)

拥有一个标志是一种很好的方法,但请记住,您需要在某种程度上实际存储标志的状态,并在每次数据更改时重新绑定它。我为这个演示选择了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; }
}