i have a code i want to apply sorting on department column of my gridview so that when i click on department then all data should be sort asc order but its not working.
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IPPhoneDirectory
{
public partial class SearchTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
PopulateDepartmentDropdown();
}
}
private void BindGridView()
{
string query = "SELECT ext as Extensions, description as Name, department as Department, station as Station FROM users";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
// Check if a department is selected
if (DropDept.SelectedIndex > 0) // Assuming "All" is at index 0
{
query += " WHERE department = @department";
}
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
// Add department parameter if a department is selected
if (DropDept.SelectedIndex > 0)
{
cmd.Parameters.AddWithValue("@department", DropDept.SelectedValue);
}
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
[WebMethod]
[ScriptMethod]
public static List<string> GetSearchSuggestions(string input)
{
List<string> suggestions = new List<string>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT ext, description, department, station FROM users WHERE description LIKE @search OR ext LIKE @search ORDER BY description ASC";
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@search", "%" + input + "%");
con.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string suggestion = string.Format("{0} - {1} - {2} - {3}",
reader["ext"].ToString(),
reader["description"].ToString(),
reader["department"].ToString(),
reader["station"].ToString());
suggestions.Add(suggestion);
}
}
}
}
return suggestions;
}
private void PopulateDepartmentDropdown()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT DISTINCT department FROM users ORDER BY department";
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
con.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
DropDept.Items.Clear(); // Clear existing items
DropDept.Items.Add(new ListItem("All", "")); // Add "All" option
while (reader.Read())
{
ListItem item = new ListItem(reader["department"].ToString(), reader["department"].ToString());
DropDept.Items.Add(item);
}
}
}
}
}
protected void DropDept_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridView();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
string sortDirection = "ASC";
string lastDirection = ViewState["SortDirection"] as string;
if (lastDirection != null)
{
if (lastDirection.Equals("ASC") && column.Equals(ViewState["SortExpression"]))
{
sortDirection = "DESC";
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SearchTest.aspx.cs" Inherits="IPPhoneDirectory.SearchTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Airblue IP Phones Directory</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Sofia+Sans+Condensed:wght@400;700&display=swap');
body {
font-family: 'Sofia Sans Condensed', sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
#container {
padding: 10px;
border-radius: 10px;
text-align: center;
width: 100%;
margin: 15px auto;
background-color: #fff;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
h1 {
display: flex;
justify-content: center;
align-items: center;
color: black;
margin-bottom: 20px;
}
#search {
margin-bottom: 20px;
display: flex;
justify-content: center;
align-items: center;
}
#txtSearch {
padding: 10px;
border: 2px solid #4CAF50;
border-radius: 5px;
margin-right: 10px;
width: 400px;
}
#DropDept {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: 2px solid #4CAF50;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
font-family: 'Sofia Sans Condensed', sans-serif;
font-size:16px;
}
#DropDept option {
background-color: white;
color: black;
}
#DropDept:hover {
background-color: #45a049;
border-color: #45a049;
}
#DropDept option:checked {
background-color: #4CAF50;
color: white;
}
#GridView1 {
width: 100%;
border-collapse: collapse;
}
#GridView1 th, #GridView1 td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
#GridView1 th {
background-color: #f2f2f2;
color: #333;
}
#GridView1 tr:nth-child(even) {
background-color: #f9f9f9;
}
#GridView1 tr:hover {
background-color: #f0f0f0;
}
.styledGridView {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.styledGridView th, .styledGridView td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.styledGridView th {
background-color: #f2f2f2;
color: #333;
}
.styledGridView tr:nth-child(even) {
background-color: #f9f9f9;
}
.styledGridView tr:hover {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<h1>Airblue IP Phones Directory</h1>
<div id="search">
<asp:TextBox ID="txtSearch" runat="server" autocomplete="off" placeholder="Search for contacts by name or extension..."></asp:TextBox>
<asp:DropDownList ID="DropDept" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDept_SelectedIndexChanged"></asp:DropDownList>
</div>
<div id="searchSuggestions"></div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" OnSorting="GridView1_Sorting">
</asp:GridView>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Function to handle suggestion click
$(document).on("click", "#searchSuggestions div", function () {
var suggestion = $(this).text();
$("#txtSearch").val(suggestion);
$("#searchSuggestions").empty();
fetchResult(suggestion);
});
// Function to fetch and display result for a name
function fetchResult(name) {
$.ajax({
type: "POST",
url: "SearchTest.aspx/GetResultForName",
data: '{name: "' + name + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#GridView1").html(response.d);
}
});
}
// Function to handle input event
$("#txtSearch").on("input", function () {
var input = $(this).val();
$.ajax({
type: "POST",
url: "SearchTest.aspx/GetSearchSuggestions",
data: '{input: "' + input + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#searchSuggestions").empty();
var tableHtml = '<table id="suggestionTable" class="styledGridView">';
tableHtml += '<thead><tr><th>Extensions</th><th>Name</th><th>Department</th><th>Station</th></tr></thead>';
tableHtml += '<tbody>';
$.each(response.d, function (index, item) {
var fields = item.split(' - ');
tableHtml += '<tr>';
$.each(fields, function (index, field) {
tableHtml += '<td>' + field + '</td>';
});
tableHtml += '</tr>';
});
tableHtml += '</tbody></table>';
$("#searchSuggestions").append(tableHtml);
// Hide the GridView
$("#GridView1").hide();
}
});
});
});
</script>
</form>
</body>
</html>