How to bind datatable with different table to already sorted gridview

114 Views Asked by At

I am creating a dynamic application. Where I am giving add,update,delete,paging and sorting options. I have one on top drop-down where I am placing table names in option. Problem is that when I select one table and sort it and change the table from drop-down it showing an error that cannot find column A(By which I have done sorting in previous table.)

Here is my code.

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortdir = string.Empty;
            if (dir == SortDirection.Ascending)
            {
                dir = SortDirection.Descending;
                sortdir = "Desc";
                sortImage.ImageUrl = "../Images/asc.gif";
            }
            else
            {
                dir = SortDirection.Ascending;
                sortdir = "Asc";
                sortImage.ImageUrl = "../Images/desc.gif";
            }

            DataView sortedView = new DataView(dt);
            sortString = e.SortExpression + " " + sortdir;
            sortedView.Sort = sortString;
            ViewState.Add("View", dt);
            ViewState.Add("sortString", sortString);
            gv.DataSource = sortedView;
            gv.DataBind();
            int columnIndex = 0;
            foreach (DataControlFieldHeaderCell headerCell in gv.HeaderRow.Cells)
            {
                if (headerCell.ContainingField.SortExpression == e.SortExpression)
                {
                    columnIndex = gv.HeaderRow.Cells.GetCellIndex(headerCell);
                }
            }
            gv.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);

        }
        catch (Exception ex)
        {
            AMP1.Title = "Unable to Get Data.!";
            AMP1.Message = ex.Message;
            AMP1.MessageDescription = ex.StackTrace;
            AMP1.AppMessageType = TEMP.Controls.AplicationMessagePanel.MessageType.Error;
            ((Button)AMP1.FindControl("btnOK")).CausesValidation = false;
            ((Button)AMP1.FindControl("btnOK")).Focus();
            ModalPopupExtenderException.Show();
        }
    }


public void createGrid(DataTable dtTable)
    {
        try
        {
            // setting flag to get first dropdownlist name
            bool flag = true;

            dtTable.Columns.Add("SrNo", typeof(String)).SetOrdinal(0);

            //Clearing all the columns before adding new one
            gv.Columns.Clear();
            int count = gv.Columns.Count - 1;



            // Creating Columns for the grid
            for (int i = 0; i < dtTable.Columns.Count; i++)
            {
                string colName = dtTable.Columns[i].ColumnName;
                TemplateField lname = new TemplateField();

                if (HeaderText(colName) != "")
                {
                    lname.HeaderText = HeaderText(colName);// +"<font color='red'>*</font>";
                }
                else
                {
                    lname.HeaderText = colName;// +"<font color='red'>*</font>"; ;
                }

                if (colName != "SrNo")
                {
                    lname.SortExpression = colName;
                }
                if (colName != "ID" && colName != "Active" && colName != "SrNo" && colName != "BModelValue_Val")
                {
                    lname.ItemStyle.CssClass = "tr1";
                    lname.FooterStyle.CssClass = "tr2";
                }
                else
                {
                    if (colName == "BModelValue_Val")
                    {
                        lname.ItemStyle.CssClass = "tdBeveWorm";
                        lname.FooterStyle.CssClass = "tdBeveWorm";
                    }
                    else
                    {
                        lname.ItemStyle.CssClass = "tr1";
                        lname.FooterStyle.CssClass = "tr2";
                    }
                }

                if (colName.EndsWith("_Val") || colName == "ID" || colName == "SrNo")
                {
                    lname.ItemTemplate = new AddTemplateToGrid(AddTemplateToGrid.enumControlType.Label, colName);

                    if (colName.EndsWith("_Val") && flag == true)
                    {
                        firstddl = colName;
                        flag = false;
                    }



                    if (colName != "ID" && colName != "SrNo")
                        lname.FooterTemplate = new AddTemplateToGrid("footer", AddTemplateToGrid.enumControlType.DropDownList, colName);
                }
                else
                {
                    if (colName == "Active")
                    {
                        lname.ItemTemplate = new AddTemplateToGrid(AddTemplateToGrid.enumControlType.CheckBox, colName);
                        lname.FooterTemplate = new AddTemplateToGrid("footer", AddTemplateToGrid.enumControlType.CheckBox, colName);
                    }
                    else
                    {
                        lname.ItemTemplate = new AddTemplateToGrid(AddTemplateToGrid.enumControlType.TextBox, colName);
                        lname.FooterTemplate = new AddTemplateToGrid("footer", AddTemplateToGrid.enumControlType.TextBox, colName);

                    }
                }

                gv.Columns.Add(lname);
            }
            // Command Buttons for Grid
            TemplateField lname1 = new TemplateField();
            lname1.HeaderText = "Action";
            lname1.ItemTemplate = new AddTemplateToGrid("Item", AddTemplateToGrid.enumControlType.ImageButton, "Action");
            lname1.FooterTemplate = new AddTemplateToGrid("footer", AddTemplateToGrid.enumControlType.ImageButton, "Action");
            //lname1.FooterStyle.Width = new Unit("150px");
            //lname1.ItemStyle.Width = new Unit("150px"); 
            gv.Columns.Add(lname1);
            gv.AutoGenerateColumns = false;

            // Checking whether page is sorted or not
            if (ViewState["View"] != null)
            {
                DataView dv1 = new DataView(dtTable);
                dv1.Sort = ViewState["sortString"].ToString();
                // Binding DataView to the Grid
                gv.DataSource = dv1;
            }
            else
            {
                // Binding DataTable to the Grid
                gv.DataSource = dtTable;
            }
            gv.DataBind();


            //Checking Page is having Index or not and setting HiddenField Value.
            if (dtTable.Rows.Count > gv.PageSize)
                hdfPagindex.Value = "1";
            else
                hdfPagindex.Value = "0";
        }
        catch (Exception ex)
        {
            AMP1.Title = "Unable to Get Data.!";
            AMP1.Message = ex.Message;
            AMP1.MessageDescription = ex.StackTrace;
            AMP1.AppMessageType = TEMP.Controls.AplicationMessagePanel.MessageType.Error;
            ((Button)AMP1.FindControl("btnOK")).CausesValidation = false;
            ((Button)AMP1.FindControl("btnOK")).Focus();
            ModalPopupExtenderException.Show();
        }
    }


public void loadTable(string tblName)
    {
        // Getting Table records
        dt = null;
        dt = bl.BindDataToMaster(tblName);

        // Creating grid according to DataTable
        gv.Columns.Clear();

        createGrid(dt);

    }



protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            ViewState["View"] = null;
            ViewState["sortString"] = null;

            tblName = ddl.SelectedItem.Value;
            gv.PageIndex = 0;
            loadTable(tblName);
        }
        catch (Exception ex)
        {
            AMP1.Title = "Unable to Get Data.!";
            AMP1.Message = ex.Message;
            AMP1.MessageDescription = ex.StackTrace;
            AMP1.AppMessageType = WEIR_BDK.Controls.AplicationMessagePanel.MessageType.Error;
            ((Button)AMP1.FindControl("btnOK")).CausesValidation = false;
            ((Button)AMP1.FindControl("btnOK")).Focus();
            ModalPopupExtenderException.Show();
        }
    } //DropDownList Index Changed
1

There are 1 best solutions below

0
marsahllDTitch On

Each Data element in ASP.net has two things, the first one is the DataSource, it's where the data element get the data, and the second one is a method called DataBind, it's a void method, example: Let's assume that my GridView is named grid and the DataTable name dt_table, and the my grid is filled with the data, but my data table is not, so if i want to fill my grid view, i just simply need to add this code :

dt_table.DataSource = grid.ToArray();
dt_table.DataBind();

Greetings.