如何正确数据绑定gridview?

时间:2011-12-06 17:39:06

标签: c# asp.net

所以我有一个包含gridview的页面,girdview通过web服务从objectdatasource获取它的数据。它包含2个带有itemtemplates的列。对于处于编辑模式的每个模板,包含存储在edititemtemplates下的下拉列表。

一切似乎都运行正常,除非我处于编辑模式并触发更新事件,我的下拉列表会抛出一个空引用错误。经过进一步调查,似乎这似乎是由于代码隐藏思维导致无法找到滴滴列表。此外,在挖掘调试器时,似乎下拉列表似乎不存在。 虽然,在我的页面上,当处于编辑模式时,下拉列表会显示,但代码隐藏无法找到这些控件。

我猜测的是我在错误的位置绑定了gridview,或者绑定本身是错误的。

我想知道的是,为什么会出现这种情况,我该如何解决? 如果我能正确地进行绑定,有人可以告诉我,我也很感激。

您将在下面找到gridview及其代码隐藏的代码。

GridView的:

<asp:GridView ID="GridViewHolder" 
                      runat="server" 
                      AllowPaging="True" 
                      AutoGenerateColumns="False" 
                      BackColor="Transparent" 
                      BorderColor="#999999" 
                      BorderStyle="Ridge" 
                      BorderWidth="3px" 
                      CellPadding="4" 
                      CellSpacing="2" 
                      DataSourceID="MachineDataSet" 
                      ForeColor="Black" 
                      HeaderStyle-HorizontalAlign="Center" 
                      HorizontalAlign="Center"  
                      RowStyle-HorizontalAlign="Center" 
                      Width="796px"
                      OnRowUpdating="GridViewHolder_Updating"
                      OnRowCancelingEdit="GridViewHolder_Canceling"
                      OnRowEditing="GridViewHolder_Editing"
                      OnRowCommand="GridViewHolder_RowCommand"                                                    
                      EnableViewState="False">
            <RowStyle BackColor="Transparent" 
                      HorizontalAlign="Center" />
            <Columns>
                <asp:TemplateField HeaderText="ID" 
                                   SortExpression="ID" 
                                   Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="MachineIDLabel" 
                                   runat="server" 
                                   Text='<%# Bind("ID") %>'
                                   Visible="false"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="MachineIDText" 
                                     runat="server" 
                                     Text='<%# Bind("ID") %>'>
                        </asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="SiteName" 
                                HeaderText="Site Name" 
                                SortExpression="SiteName"
                                ReadOnly="true" />
                <asp:BoundField DataField="Name" 
                                HeaderText="Machine Name" 
                                ReadOnly="true" 
                                SortExpression="Name" />
                <asp:TemplateField HeaderText="Machine Type" 
                                   SortExpression="MachineType">
                    <ItemTemplate>
                        <asp:Label ID="MachineTypeLabel" 
                                   runat="server" 
                                   Text='<%# Bind("MachineType") %>'>
                        </asp:Label>                            
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="MachineTypeDropDown" 
                                          runat="server" 
                                          AppendDataBoundItems="True"                                                
                                          Height="21px" 
                                          Width="217px" 
                                          DataSourceID="GetMachineType" 
                                          DataTextField="Name"                                              
                                          DataValueField="ID">                                              
                            <asp:ListItem Enabled="true" 
                                          Text="Select a Machine Type." 
                                          Value="empty">
                            </asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Machine Model" SortExpression="MachineModel">
                    <ItemTemplate>
                        <asp:Label ID="MachineModelLabel" 
                                   runat="server" 
                                   Text='<%# Bind("MachineModel") %>'>
                        </asp:Label>                            
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="MachineModelDropDown" 
                                          runat="server" 
                                          AppendDataBoundItems="True"                                                
                                          Height="21px" Width="217px" 
                                          DataSourceID="GetMachineModel" 
                                          DataTextField="Name" 
                                          DataValueField="ID">                                              
                            <asp:ListItem Enabled="true" 
                                          Text="Select a Machine Model." 
                                          Value="empty">
                            </asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ButtonType="Button" 
                                  ShowEditButton="True"
                                  CausesValidation="false" >
                    <ItemStyle HorizontalAlign="Center" 
                               Wrap="True" />
                </asp:CommandField>
            </Columns>
            <FooterStyle BackColor="Transparent" />
            <PagerStyle BackColor="Transparent" 
                        ForeColor="Black" 
                        HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="Transparent" 
                              Font-Bold="True" 
                              ForeColor="White" />
            <HeaderStyle BackColor="Black" 
                         Font-Bold="True" 
                         ForeColor="White" 
                         HorizontalAlign="Center" />
     </asp:GridView>

代码隐藏:

Pageload方法:

        /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        logger.Debug("Entering Page_Load");
        Boolean loginRequired = true;
        // If no login is required set the session variable and proceed to the main page.
        string str = ConfigurationManager.AppSettings["i0"] as string;
        if (!string.IsNullOrEmpty(str))
        {
            string flag = MyExtensions.Decrypt(str, true);
            if ("false".Equals(flag, StringComparison.InvariantCultureIgnoreCase))
                loginRequired = true;
            else
            {
                loginRequired = false;

                // User logged in so check the permissions.
                UserInfo user = (UserInfo)Session[Constants.LOGGEDINUSER];
                if (null == user)
                    loginRequired = true;
                else
                {
                    string groupId = user.GroupId;
                    if (string.IsNullOrEmpty(groupId))
                        loginRequired = true;
                    else if (!"Admins".Equals(user.GroupId) && !"Engineer".Equals(user.GroupId))
                        loginRequired = true;
                }
            }
        }
        if (!Page.IsPostBack)
        {
            Control ctrl = MyExtensions.FindControlRecursive(this, "CommissioningLoginPanel");
            Panel loginPanel = null;
            Panel contentPanel = null;

            if (null != ctrl)
            {
                loginPanel = (Panel)ctrl;
                ctrl = MyExtensions.FindControlRecursive(this, "CommissioningPanel");
                if (null != ctrl)
                    contentPanel = (Panel)ctrl;
            }

            if (loginRequired)
            {
                if (null != loginPanel)
                    loginPanel.Visible = true;
                if (null != contentPanel)
                    contentPanel.Visible = false;
            }
            else
            {
                if (null != loginPanel)
                    loginPanel.Visible = false;
                if (null != contentPanel)
                    contentPanel.Visible = true;
            }                
        }
        BindData();
        logger.Debug("Leaving Page_Load");
    }

gridview事件:

        /// <summary>
    /// Handles the Click event of the update button under edit in the gridview control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
    protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e) 
    {
        logger.Debug("Entering GridviewHolder_Updating");
        int machineid;
        string machineid1;
        string machineTypeid;
        string machineModelid;

        //retrieve and set the data
        GridViewHolder.EditIndex = e.RowIndex;

        try
        {

            GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
            TextBox mID = row.FindControl("MachineIDText") as TextBox;
            DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
            DropDownList mModel = row.FindControl("MachineModelDropDown") as DropDownList;

            machineid1 = mID.Text;
            machineid = Convert.ToInt32(machineid1);
            machineTypeid = mType.SelectedValue;
            machineModelid = mModel.SelectedValue;


            try
            {
                if (machineTypeid != "empty" || machineModelid != "empty")
                {
                    if (machineTypeid != "empty")
                    {
                        inputsService.UpdateMachineTypes(machineid, machineTypeid);
                    }
                    if (machineModelid != "empty")
                    {
                        inputsService.UpdateMachineModels(machineid, machineModelid);
                    }
                    UpdateSucceed.Visible = true;
                    logger.Debug("Updating - Database successfully updated!");
                }
                else
                {
                    UpdateFail.Visible = true;
                    logger.Debug("Updating - Database had no data selected to be updated.");
                }
            }
            catch (Exception ex)
            {
                logger.ErrorFormat("Updating - Failed to update the table, ex = {0}", ex);
            }
        }
        catch (Exception ex)
        {
            logger.ErrorFormat("Updating.gathering page controls - Failed to update the table, ex = {0}", ex);
        }
        logger.Debug("Leaving GridViewHolder_Updating");
    }

    /// <summary>
    /// Handles the Click event of the cancel button under edit in the gridview control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
    protected void GridViewHolder_Canceling(object sender, GridViewCancelEditEventArgs e)
    {
        logger.Debug("Entering GridViewHolder_Canceling");
        //reset the edit index
        GridViewHolder.EditIndex = -1;
        //Bind data to GridViewHolder
        BindData();
        logger.Debug("Leaving GridViewHolder_Canceling");
    }

    /// <summary>
    /// Handles the Click event of the cancel button under edit in the gridview control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
    protected void GridViewHolder_Editing(object sender, GridViewEditEventArgs e)
    {
        logger.Debug("Entering GridViewHolder_Editing");        
        //set the edit index to a new value
        GridViewHolder.EditIndex = e.NewEditIndex;
        //Bind data to gridviewholder
        BindData();
        logger.Debug("Leaving GridViewHolder_Editing");
    }

BindData方法:

 private void BindData()
    {
        logger.Debug("Entering DataBind");
        GridViewHolder.DataSource = Session["MachineTable"];
        GridViewHolder.DataBind();
        logger.Debug("Leaving DataBind");
    }

非常感谢任何帮助或建议。

谢谢

2 个答案:

答案 0 :(得分:1)

您是否尝试在gridview中设置EnableViewState="True"

当回发发生时没有启用视图状态的asp可能不知道回发发生时下拉列表的状态。

答案 1 :(得分:1)

您能否尝试将gridview的DataKeyNames属性设置为您正在使用gridview格式的表的id

<asp:GridView ID="gvEmployees" runat="server" DataKeyNames="EmployeeId" ...