回发后Gridview数据源为null

时间:2013-12-10 12:02:05

标签: c# asp.net gridview

我有一个带有gridview的页面,用于显示文章组,以及搜索组的文本框和搜索按钮。 在此页面中如果用户不搜索任何内容,网格视图仅显示主要组(使用parentId 0) 并显示每个组,组名称包含文本框值。 我的问题是当我搜索,然后我想更新一些行,GridView1_RowUpdating没有被解雇... 我发现问题是gridview数据源没有成功绑定。 我该如何解决这个问题? 以下是我的来源:

<asp:Label ID="Label1" runat="server" CssClass="txt" Text="searchgroups " ForeColor="#68a2d7"></asp:Label>

                    <asp:Label ID="Label2" runat="server" CssClass="txt" Text="group name" ForeColor="#68a2d7"></asp:Label>

                    <asp:TextBox ID="txtname" runat="server" CssClass="txt" Width="300px"></asp:TextBox>

           <br/>

                    <asp:ImageButton ID="Ibtnsearch" runat="server" ImageAlign="Left" ImageUrl="../Icon/resize/search.gif"
                        OnClick="Ibtnsearch_Click" />
                <br/>
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                        ForeColor="#333333" GridLines="None" Width="100%" CssClass="txt" AllowPaging="True"
                        OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
                        OnRowUpdating="GridView1_RowUpdating" OnPageIndexChanging="GridView1_PageIndexChanging"
                        OnRowCommand="GridView1_RowCommand1" PageSize="15" AllowSorting="True" OnSorting="GridView1_Sorting">
                        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <Columns>

                            <asp:BoundField DataField="chid" SortExpression="chid" HeaderText="ID" />
                            <asp:BoundField DataField="chname" SortExpression="chname" HeaderText="Name" />


                            <asp:HyperLinkField DataNavigateUrlFields="chid,cLanguage" DataNavigateUrlFormatString="../default.aspx?pnl=lstcatChat&amp;nParentid_fk={0}&lang={1}"
                                Text="Sub Groups" HeaderText="Show Sub Grups">
                                <ControlStyle CssClass="link" />
                            </asp:HyperLinkField>

                            <asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
                                ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
                                EditText="Edit" HeaderText="Edit" />

                        </Columns>
                        <RowStyle BackColor="#e8edf2" ForeColor="#333333" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        <PagerStyle BackColor="White" ForeColor="#333333" HorizontalAlign="Center" BorderColor="White"
                            Font-Bold="True" Font-Names="Tahoma" Font-Overline="False" Font-Size="X-Small"
                            Font-Underline="False" />
                        <HeaderStyle BackColor="#68a2d7" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
                        <AlternatingRowStyle BackColor="White" />
                        <PagerSettings Mode="NumericFirstLast" />
                    </asp:GridView>

并在我的代码页中:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = Search_groups();
            GridView1.DataBind();
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.DataSource = Search_groups();
        if (GridViewSortExpresion != null && GridViewSortExpresion != "")
            SortGridView(GridViewSortExpresion, GridViewSortDirection);
        GridView1.EditIndex = e.NewEditIndex;
        GridView1.DataBind();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.DataSource = Search_groups();
        if (GridViewSortExpresion != null && GridViewSortExpresion != "")
            SortGridView(GridViewSortExpresion, GridViewSortDirection);
        GridView1.EditIndex = -1;
        GridView1.DataBind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gvr = GridView1.Rows[e.RowIndex];
        using (_Category nc = new _Category())
        {
            if (Request["lang"] == "" || Request["lang"] == null)
                nc.Language = "fa";
            else
                nc.Language = Request["lang"];
            DataTable dt2 = new DataTable();
            dt2 = Search_groups();
            int ncid = (int)dt2.Rows[e.RowIndex]["chid"];
            ncid = Convert.ToInt32(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text);
            nc.ID = ncid;
            nc.Name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            nc.Updatefast();

            GridView1.DataSource = Search_groups();
            if (GridViewSortExpresion != null && GridViewSortExpresion != "")
                SortGridView(GridViewSortExpresion, GridViewSortDirection);
            GridView1.EditIndex = -1;
            GridView1.DataBind();
            dt2.Dispose();
            gvr.Dispose();
        }
    }

    protected void Ibtnsearch_Click(object sender, ImageClickEventArgs e)
    {
        GridView1.DataSource = Search_groups();
        if (GridViewSortExpresion != null && GridViewSortExpresion != "")
            SortGridView(GridViewSortExpresion, GridViewSortDirection);
        GridView1.DataBind();
    }

    private DataTable Search_groups()
    {
        if (Request["nParentid_fk"] != null)
            parent_fk = Convert.ToInt32(Request["nParentid_fk"]);
        else
            parent_fk = 0;
        using (_Category nc = new _Category())
        {
            if (Request["lang"] == "" || Request["lang"] == null)
                nc.Language = "fa";
            else
                nc.Language = Request["lang"];
            if (txtname.Text != "")
                return nc.search_allcategories(txtname.Text);
            else
                return nc.Select_parentid_fk(parent_fk);

        }
    }

    public string GridViewSortDirection
    {
        get
        {
            //if (ViewState["sortDirection"] == null)
            //    ViewState["sortDirection"] = SortDirection.Ascending;

            //return (SortDirection)ViewState["sortDirection"];
            if (SortDirection.Value == null)
                SortDirection.Value = "asc";

            return SortDirection.Value;
        }
        set { SortDirection.Value = value; }
    }

    public string GridViewSortExpresion
    {
        get
        {
            //if (ViewState["SortExpresion"] == null)
            //    ViewState["SortExpresion"] = "";
            //if (ViewState["SortExpresion"] != null)
            //    return ViewState["SortExpresion"].ToString();
            //else
            //    return null;
            if (SortExpresion.Value != null)
                return SortExpresion.Value.ToString();
            else
                return null;
        }
        set { SortExpresion.Value = value; }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        //DataTable dataTable = GridView1.DataSource as DataTable;

        GridViewSortExpresion = e.SortExpression;
        if (GridViewSortDirection == "asc")
        {

            GridViewSortDirection = "desc";
            SortGridView(GridViewSortExpresion, GridViewSortDirection);
        }
        else
        {

            GridViewSortDirection = "asc";
            SortGridView(GridViewSortExpresion, GridViewSortDirection);
        }
    }

    private void SortGridView(string sortExpression, string direction)
    {
        //  You can cache the DataTable for improving performance
        //DataTable dt = GridView1.DataSource as DataTable;
        DataTable dt = Search_groups();
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + " " + direction;

        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

当我尝试更新时,我收到此错误:

  

指数超出范围。必须是非负数且小于集合的大小。   参数名称:index

修改2

现在我发现我的问题是gridview在post back上丢失了数据源, 我搜索但我找不到解决方案。我不想使用session或viewstate,因为我有很多像上面这样的表,解决方案是什么?

1 个答案:

答案 0 :(得分:1)

设置以下属性:

设置AutoGenerateEditButton="False"

尝试推杆:

<asp:TemplateField>
    <ItemTemplate>
            <asp:Button id="btnEdit" runat="server" commandname="Edit" text="Edit" />
            <asp:Button id="btnDelete" runat="server" commandname="Delete" text="Delete" />
    </ItemTemplate>
    <EditItemTemplate>
            <asp:Button id="btnUpdate" runat="server" commandname="Update" text="Update" />
            <asp:Button id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
    </EditItemTemplate>
</asp:TemplateField>

取代:

<asp:CommandField CausesValidation="false" ButtonType="Image" EditImageUrl="~/Icon/silk/application_edit.gif"
                                ShowEditButton="True" CancelImageUrl="~/Icon/silk/arrow_undo.gif" UpdateImageUrl="~/Icon/silk/accept.gif"
                                EditText="Edit" HeaderText="Edit" />