mina morsali
mina morsali

Reputation: 778

Gridview datasource is null after postback

I have a page with a gridview that show article groups,and textbox and search button for search groups. in this page if user not search anything ,grid view only show main groups(with parentId 0) and else show every group that group name's contain textbox value. My problem is when I search ,and then I want to update some row,GridView1_RowUpdating not fired... I found that the problem is that gridview datasource not bound successfully. how I fix this problem? below is my source:

<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>

and in my code page:

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();
    }

when I try to update ,I get this error:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Edit 2

Now I found that my problem is that gridview loses datasource on post back , I search but I not found solution.I don't want to use session or viewstate,because I have a lot of tables like above ,What is the solution?

Upvotes: 1

Views: 2864

Answers (1)

C Sharper
C Sharper

Reputation: 8626

set following property:

set AutoGenerateEditButton="False"

Try putting:

<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>

In place of :

<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" />

Upvotes: 1

Related Questions