asp.net如何解析GridView?

时间:2010-07-15 03:54:12

标签: c# asp.net gridview

asp.net如何解析GridView?假设我已经定义了EditItemTemplate和ItemTemplate。似乎我无法在加载时将任何数据绑定到控件,如EditItemTemplate中的dropdownlist。

当激活编辑模式时,数据是否会绑定到EditItemTemplate中的控件?如果没有,如何在C#中加载时绑定所有控件?

谢谢,这实际上让我发疯了。我找不到任何关于asp.net如何在线执行或评估GridView的信息。

3 个答案:

答案 0 :(得分:1)

您需要在进入编辑模式时进行绑定。请记住,编辑控件在设置为特定行的编辑模式之前不存在。那时控件可以绑定。

通常,如果您要在编辑模式下绑定常见的查找类型数据,我会在第一次将其加载到CacheSessionViewState(取决于内容和情况)它是必需的,然后从这个'缓存'位置绑定它以保存数据库调用。我通常为OnDataBinding中需要特殊绑定的每个控件实现EditItemTemplate方法,如DropDownList

在你的aspx中:

<EditItemTemplate>
    <asp:DropDownList ID="yourDropDownList" runat="server" 
        OnDataBinding="yourDropDownList_DataBinding"></asp:DropDownList>
</EditItemTemplate>

然后在你的代码隐藏中:

protected void yourDropDownList_DataBinding(object sender, System.EventArgs e) 
{ 
    DropDownList ddl = (DropDownList)(sender);
    // do you databinding code here

    // this is an example
    ddl.DataSource = GetMyDropDownListData();
    ddl.DataBind();
    ddl.SelectedValue = Eval("FieldFromGridData");
}

我更喜欢以这种方式绑定,因为它会将代码本地化为特定控件,而您不必在行等上使用FindControl来查找它们......

yourDropDownList_DataBinding只会在编辑模式下为该行触发。在没有任何处于编辑模式的初始绑定中,数据绑定不会触发,但每次将行放入编辑模式时它都会执行,这就是为什么我说以某种方式缓存要绑定到{{1}的数据的原因你第一次得到它。

答案 1 :(得分:0)

尝试使用Eval设置网格以从gridview的数据源获取数据。

    <asp:GridView ID="gv" runat="server" SkinID="gridviewSkin" AutoGenerateColumns="False" DataKeyNames="Id"
                AutoGenerateEditButton="false"
                OnRowEditing="GvItems_RowEditing"
                OnRowCancelingEdit="GvItems_RowCancelingEdit"
                OnRowUpdating="GvItems_RowUpdating"
                OnPageIndexChanging="Gv_PageIndexChanging"
                AllowPaging="true"
                PageSize="20"
        >
    <Columns>
        <asp:CommandField ShowEditButton="True" CausesValidation="true" />
        <asp:TemplateField HeaderText="Name" ItemStyle-Width="200" ItemStyle-VerticalAlign="Top">
            <ItemTemplate>
                <%# Eval("Name")%>
            </ItemTemplate>
            <EditItemTemplate>        
                <asp:TextBox ID="txtName" runat="server" Width="200" Text='<%# Eval("Name") %>' MaxLength="50" />
                <asp:RequiredFieldValidator ID="rfv_txtName" runat="server" ControlToValidate="txtName" Display="Dynamic" ErrorMessage="(Required)" />
            </EditItemTemplate>
        </asp:TemplateField>    
        <asp:TemplateField HeaderText="Active" ItemStyle-Width="100" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:CheckBox ID="chkActive_Item" runat="server" Checked='<%# (bool)Eval("IsActive")%>' Enabled="false" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:CheckBox ID="chkActive_Edit" runat="server" Checked='<%# (bool)Eval("IsActive")%>' />
            </EditItemTemplate>
        </asp:TemplateField>        
    </Columns>
    <EmptyDataTemplate>No items exist</EmptyDataTemplate>
</asp:GridView>

要编辑,然后

protected void GvItems_RowEditing(object sender, GridViewEditEventArgs e)
{
   gv.EditIndex = e.NewEditIndex;

   //also reload and bind the items

}

用于加载下拉数据源:

        <asp:TemplateField HeaderText="Channel Type" ItemStyle-Width="200" ItemStyle-VerticalAlign="Top">
            <ItemTemplate>
                <%# Eval("ChannelType.Name") %>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="ddlChannelType" runat="server" DataSource="<%# GetChannelTypeDropdownBoxDataSource() %>" DataTextField="Name" DataValueField="Id" AppendDataBoundItems="true" SelectedValue='<%# Eval("ChannelId") %>' />
            </EditItemTemplate>
        </asp:TemplateField>

让代码返回数据源:

    protected ChannelType[] GetChannelTypeDropdownBoxDataSource()
    {
        return _channelTypeRepository.GetAll();
    }

答案 2 :(得分:0)

在GridView模板中有许多用于数据绑定嵌套控件的选项。

最简单的,也就是我可以使用的那个,就是使用ObjectDataSource并将你的下拉列表与之绑定。

如果这不是一个选项,那么您可以在RowDataBound事件中绑定。缺少example on MSDN,但是如果您遵循该示例(C#),并且其中包含:

 // Display the company name in italics.
      e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";

你会有类似的东西:

DropDownList ddlWhatever = e.Row.FindControl("ddlWhatever") as DropDownList;
if(ddlWhatever != null) { /* bind data to it and call ddlWhatever.DataBind(); */ }

由于EditItemTemplate和InsertItemTemplate不会同时呈现,我通常会在每个模板中保持控件名称相同,以简化后面代码中的数据绑定事件。但是,没有什么能阻止你拥有ddlEditItemsddlInsertItems并在数据绑定事件中以不同方式绑定它们。

我之前使用的另一个技巧是使用下拉列表的OnInit事件绑定到DropDownList。例如:

// web form
<asp:DropDownList id="ddlWhatever" AutoPostBack="True" 
     runat="server" OnInit="ddlWhatever_Init">

// Code behind
protected void ddlWhatever_Init(object s, EventArgs a)
{       
   object[] years = {
     new { Year = 2009 }, new { Year = 2010 }
   };
   ddlWhatever.DataSource = years;
   ddlWhatever.DataTextField = "Year";
   ddlWhatever.DataValueField = "Year";
   ddlWhatever.DataBind();
}

我有一些人告诉我不要这样做(也就是说控件不应该对绑定本身负责)。我不同意,也不记得在微软的框架设计指南中看到与该声明相关的任何内容。当它归结为它时,我喜欢最后一种方式,当我不能使用ObjectDataSource时,但我也必须编写其他开发人员的接受程度。 :d

我通常坚持的规则:

  1. 快速简便地使用ObjectDataSource
  2. 当嵌套控件的项依赖于GridView中的其他值时使用GridView RowDataBound
  3. 如果您只是绑定数据,请使用OnInit方法,请记住在触发此方法时无法访问其他控件(例如,GridView可能尚未初始化)
  4. 我希望有所帮助,我对MSDN缺乏GridView示例时遇到了类似的挫败感。