private void LoadData(string strSortCol, string strSortOrder) { // this function will load data into data table dataGridView1.Rows.Clear(); dataGridView1.Refresh(); dataGridView1.Columns.Clear(); dataGridView1.DataSource = null; try { DataRetriever retriever = new DataRetriever(connectionString, table, strSortCol + " " + strSortOrder); memoryCache = new Cache(retriever, Page_Size); //foreach (DataColumn column in retriever.Columns) //{ // dataGridView1.Columns.Add(column.ColumnName, column.ColumnName); //} retriever.Columns.Cast<DataColumn>().ToList().ForEach(n => dataGridView1.Columns.Add(n.ColumnName, n.ColumnName)); this.dataGridView1.RowCount = retriever.RowCount; } catch (Exception ex) { MessageBox.Show("Connection could not be established. " + "Verify that the connection string is valid."); Application.Exit(); } // Adjust the column widths based on the displayed values. this.dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); // set the sorting glyph initially when data load if (strSortOrder == "ASC") { this.dataGridView1.Columns[strSortCol].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending; } else { this.dataGridView1.Columns[strSortCol].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending; } }
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { // sorting is handle by this event handler string strSortCol = this.dataGridView1.Columns[e.ColumnIndex].Name; if (strPrevSortCol.Trim().ToUpper() != strSortCol.Trim().ToUpper()) { this.dataGridView1.Columns[strPrevSortCol].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.None; strPrevSortCol = strSortCol; strSortOrder = "ASC"; } if (this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == System.Windows.Forms.SortOrder.Ascending) { this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending; strSortOrder = "DESC"; } else if (this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == System.Windows.Forms.SortOrder.Descending) { this.dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending; strSortOrder = "ASC"; } else { if (strSortOrder == "ASC") this.dataGridView1.Columns[strSortCol].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending; else this.dataGridView1.Columns[strSortCol].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending; } dataGridView1.Rows.Clear(); DataRetriever retriever = new DataRetriever(connectionString, table, strSortCol + " " + strSortOrder); memoryCache = new Cache(retriever, Page_Size); this.dataGridView1.RowCount = retriever.RowCount; dataGridView1.Refresh(); }