I have a GridView that gets populated from a DataView as the source.
When I try to filter rows based on the RowFilter of the DataView nothing happens.
I have a textbox that allows users to enter an Item_Number to search for and should select the records from the DataView that only contain that Item_Number.
public DataTable PrintTable
{
set{Session["PrintTable"] = value;}
get
{
if(Session["PrintTable"] == null)
return null;
else
return (DataTable) Session["PrintTable"];
}
}
public DataView PrintView
{
get
{
if (PrintTable != null)
{
DataView dv = new DataView(PrintTable);
dv.AllowEdit = true;
if(SortAscend)
dv.Sort = SortColumn;
else
dv.Sort = SortColumn + " DESC";
return dv;
}
return null;
}
}
Private void BuildGrid()
{
daUnSched.SelectCommand.Parameters["#WC_Id"].Value = WC_Id.Text;
daUnSched.Fill(dsPrintTicket2.SFD10011);
PrintTable = dsPrintTicket2.SFD10011;
dgPrintTicket.DataBind();
}
private void btnGoTo_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string val = GoTo.Text.Trim();
if (val.Length > 0)
{
PrintView.RowFilter = string.Format("Item_Number = '" + val + "'");
PrintTable = PrintView.ToTable();
dgPrintTicket.DataBind();
}
}
When I enter an Item_Number and press search, the btnGoTo_Click method gets called, but its not selecting the rows based on the RowFilter.
Any Help would be appreciated.
Thank you
You have not assigned DataTable back to the GridView to show filtered results
private void btnGoTo_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string val = GoTo.Text.Trim();
if (val.Length > 0)
{
PrintView.RowFilter = string.Format("Item_Number = '" + val + "'");
PrintTable = PrintView.ToTable();
dgPrintTicket.DataSource = PrintTable; //Or assign DataView
dgPrintTicket.DataBind();
}
}
Related
I can't seem to get this right, even after looking at a few examples.
I've got this code, which happily re-sorts my gridview in an Ascending order:
// gridViewSorting and ConvertSortDirectionToSql are both necessary to ensure the gridview can sort when their column headers are
// clicked. You must remember to add (AllowSorting="True" OnSorting="gridViewSorting") to the gridview tag on the ASP side
protected void gridViewSorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GVInactive.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string SQL = "[" + e.SortExpression + "] " + ConvertSortDirectionToSql(e.SortDirection);
dataView.Sort = SQL;
GVInactive.DataSource = dataView.ToTable();
GVInactive.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "DESC";
break;
case SortDirection.Descending:
newSortDirection = "ASC";
break;
}
return newSortDirection;
}
However, the second time I click on the header it's supposed to reverse the previous sorting order. It never does. Every time I click the header of a column, it hits the case SortDirection.Ascending: line and sets newSortDirection = "DESC". The data is sorted in descending order, yet when I click the header again it resolves SortDirection to Ascending.
Any ideas?
We use a ViewState variable to store the latest Sort Direction. When the grid is sorted we compare the Sort Criteria and Sort Direction of the grid with the ViewState variables which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.
Example:
private string SortCriteria
{
get
{
if (ViewState["sortCriteria"] == null)
{
ViewState["sortCriteria"] = "";
}
return ViewState["sortCriteria"].ToString();
}
set
{
ViewState["sortCriteria"] = value;
}
}
private string SortDirection
{
get
{
if (ViewState["sortDirection"] == null)
{
ViewState["sortDirection"] = "";
}
return ViewState["sortDirection"].ToString();
}
set
{
ViewState["sortDirection"] = value;
}
}
protected void gvData_Sorting(object sender, GridViewSortEventArgs e)
{
gvData.EditIndex = -1;
if (SortCriteria == e.SortExpression)
{
if (SortDirection == string.Empty || SortDirection == "DESC") { SortDirection = "ASC"; }
else { SortDirection = "DESC"; }
}
else
{
SortCriteria = e.SortExpression;
SortDirection = "ASC";
}
BindGrid();
}
private void BindGrid()
{
DataTable dt = new [However you get dataset from database];
DataView dv = new DataView(dt);
dv.Sort = string.Format("{0} {1}", SortCriteria, SortDirection).Trim();
gvData.DataSource = dv;
gvData.DataBind();
}
For the record, I replaced the code used in my question with this, and it worked perfectly:
// gridViewSorting and ConvertSortDirectionToSql are both necessary to ensure the gridview can sort when their column headers are
// clicked. You must remember to add (AllowSorting="True" OnSorting="gridViewSorting") to the gridview tag on the ASP side
protected void gridViewSorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GVInactive.DataSource as DataTable;
string sortExpression = e.SortExpression;
string direction = string.Empty;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
DataTable table = GVInactive.DataSource as DataTable;
table.DefaultView.Sort = sortExpression + direction;
GVInactive.DataSource = table;
GVInactive.DataBind();
}
}
public SortDirection SortDirection
{
get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set
{
ViewState["SortDirection"] = value;
}
}
I can probably remove a few lines (not sure I even need the DataView anymore), but it works perfectly as is. Just remember to add these pieces to the ASP side in the GridView tag:
AllowSorting="True" OnSorting="gridViewSorting"
and then change your gridview's name where appropriate.
private void dgvComp_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dgvComp.Rows[dgvComp.CurrentRow.Index].Cells["EmplId"].ToString() != "")
{
if (dgvComp.Columns[e.ColumnIndex].Name == "EmplId")
{
{
DataTable dt = new DataTable();
string auto = dgvComp.Rows[e.RowIndex].Cells["EmplId"].EditedFormattedValue.ToString();
dt = dataAcc.rtrvData("empl_Name,empl_Id,desg_Name", "dbo.Empldmgrphcs INNER JOIN dbo.Designation ON dbo.Empldmgrphcs.desg_Id = dbo.Designation.desg_Id ", "empl_EmpId='" + auto + "'");
dgvComp.Rows[e.RowIndex].Cells["dgvname"].Value = dt.Rows[0][0].ToString();
dgvComp.Rows[e.RowIndex].Cells["empID"].Value = dt.Rows[0][1].ToString();
dgvComp.Rows[e.RowIndex].Cells["dgvdesi"].Value = dt.Rows[0][2].ToString();
}
}
}
}
The above code is what I am using to fill the DataGridView, but when a cell is empty I am getting error.
How can I handle a condition for having an empty cell?
Display a message box and set: e.Cancel = true;
private void dgvComp_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dgvComp.Rows[dgvComp.CurrentRow.Index].Cells["EmplId"].ToString() != "")
{
if (dgvComp.Columns[e.ColumnIndex].Name == "EmplId")
{
{
DataTable dt = new DataTable();
string auto = dgvComp.Rows[e.RowIndex].Cells["EmplId"].EditedFormattedValue.ToString();
dt = dataAcc.rtrvData("empl_Name,empl_Id,desg_Name", "dbo.Empldmgrphcs INNER JOIN dbo.Designation ON dbo.Empldmgrphcs.desg_Id = dbo.Designation.desg_Id ", "empl_EmpId='" + auto + "'");
if(dt.Rows.Count > 0)
{
dgvComp.Rows[e.RowIndex].Cells["dgvname"].Value = dt.Rows[0][0].ToString();
dgvComp.Rows[e.RowIndex].Cells["empID"].Value = dt.Rows[0][1].ToString();
dgvComp.Rows[e.RowIndex].Cells["dgvdesi"].Value = dt.Rows[0][2].ToString();
}
else
{
e.Cancel = true;
MessageBox.Show("Validation Fail");
}
}
}
}
}
I have a GridView with sorting enabled. For a single page result both the ascending and descending works fine. But when there are multiple pages, descending alone works well. the asceding also works but when i click on the next pages, it becomes unsorted again.
I don't know whether the problem is because of the sort direction or paging. Kindly Help.
Below are the codes:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridView grid = sender as GridView;
//Retrieve the table from the session object.
DataTable dt = Session["List"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
grid.DataSource = Session["List"];
grid.DataBind();
}
}
private string GetSortDirection(string column)
{
string sortDirection = "ASC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = bindGridView();
GridView1.DataBind();
}
You can use a session variable to store the latest Sort Expression and when you sort the grid next time compare the sort expression of the grid with the Session variable which stores last sort expression. If the columns are equal then check the direction of the previous sort and sort in the opposite direction.
DataTable sourceTable = GridAttendence.DataSource as DataTable;
DataView view = new DataView(sourceTable);
string[] sortData = Session["sortExpression"].ToString().Trim().Split(' ');
if (e.SortExpression == sortData[0])
{
if (sortData[1] == "ASC")
{
view.Sort = e.SortExpression + " " + "DESC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
}
else
{
view.Sort = e.SortExpression + " " + "ASC";
this.ViewState["sortExpression"] = e.SortExpression + " " + "ASC";
}
After so many research, I found the correct answer for my own question. This would probably help someone in future. Add the following code to the bindGridView()
if (ViewState["sortExpr"] != null)
{
dv = new DataView(ds.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
dv = ds.Tables[0].DefaultView;
and
#region Sorting
protected void Gridview1_Sort(object sender, GridViewSortEventArgs e)
{
ViewState["sortExpr"] = e.SortExpression + " " + GetSortDirection(e.SortExpression);
Gridview1.DataSource = bindGridView();
Gridview1.DataBind();
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
#endregion
I have developed an asp.net application that has a Gridview control. I want it to sort when I click on the Gridview header text in asp.net. Entity framework is used to bind the gridview.
protected void grdmortgagesaver_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
var databind = from i in mortgageentites.Clients orderby i.LastName select i;
if (databind.Count() > 0)
{
grdmortgagesaver.DataSource = databind.ToList();
grdmortgagesaver.DataBind();
DataTable dt = clients;
if (dt != null)
{
// DataTable dt = ds.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
grdmortgagesaver.DataSource = dv;
grdmortgagesaver.DataBind();
}
}
}
If you are using a standard ASP.NET System.Web.UI.WebControls.GridView, you can simply "Enable Sorting", in the properties pane by setting "AllowSorting" to true or via the "pop-out" on the top right of the control by checking "Enable Sorting"
add AllowSorting="true" in your gridview control and
protected void grd_Sorting(object sender, GridViewSortEventArgs e)
{
if (e.SortExpression == hdfSortExp.Value)
{
if (hdfUpDown.Value == "1")
hdfUpDown.Value = "0";
else
hdfUpDown.Value = "1";
}
else //New Column clicked so the default sort direction will be incorporated
hdfUpDown.Value = "0";
hdfSortExp.Value = e.SortExpression; //Update the sort column
BindGrid(hdfSortExp.Value, this.CBool(hdfUpDown.Value));
}
in your c# code
public void BindGrid(string sortBy, bool inAsc)
{
grd.DataSource = WManager.GetAdminTags(txtSearch.Text.Trim(), sortBy, inAsc);
grd.DataBind();
}
First in your Page in the GridView Declaration Tag add the property AllowSorting="true" and in the Gridview_SortCommand try the Following code as guidence
try {
if (SortType == false) {
SortView.Sort = e.SortExpression + " ASC";
//dviewGeneral.Sort = e.SortExpression & " ASC"
Session.Item("SortOrder") = SortView.Sort.ToString;
SortType = true;
} else {
SortView.Sort = e.SortExpression + " DESC";
Session.Item("SortOrder") = SortView.Sort.ToString;
//dviewGeneral.Sort = e.SortExpression & " DESC"
SortType = false;
}
CMSgrid.SelectedIndex = -1;
CMSgrid.CurrentPageIndex = 0;
SortBind();
} catch (Exception ex) {
UserMsgBox(ex.ToString());
}
I have a gridview where I bind a datasource, and I had to add sorting for this gridview; I added the code below to that, but it didn't work well.
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string m_SortDirection = String.Empty;
switch (sortDireciton)
{
case SortDirection.Ascending:
m_SortDirection = "ASC";
break;
case SortDirection.Descending:
m_SortDirection = "DESC";
break;
}
return m_SortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable m_DataTable = GridView1.DataSource as DataTable;
if (m_DataTable != null)
{
DataView m_DataView = new DataView(m_DataTable);
m_DataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = m_DataView;
GridView1.DataBind();
}
}
You can use this, as I had the same problem, and I solved it like this.
public string SortingExpression
{
get
{
if (this.ViewState["SortExpression"] == null)
return "";
else
return (string)this.ViewState["SortExpression"];
}
set
{
this.ViewState["SortExpression"] = value;
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable m_DataTable = GridView1.DataSource as DataTable;
if (m_DataTable != null)
{
DataView m_DataView = new DataView(m_DataTable);
SortingExpression = e.SortExpression + " " + (SortingExpression.Contains("ASC") ? "DESC" : "ASC");
m_DataView.Sort =SortingExpression;
GridView1.DataSource = m_DataView;
GridView1.DataBind();
}
}
Maybe this could help if your sortdirection is always ascending.
Try this out. This method worked for me.
dt is the datatable containing the values.
protected void onSorting_Gridview1(object sender, GridViewSortEventArgs e)
{
string _sortDirection = dir.ToString();
if(_sortDirection.Equals("Ascending"))
{
_sortDirection = "ASC";
dir = SortDirection.Descending;
}
else
{
_sortDirection="DESC";
dir = SortDirection.Ascending;
}
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
gridView1.DataSource = dt;
gridView1.DataBind();
}
}
public SortDirection dir
{
get
{
if (ViewState["DIR"] == null)
{
ViewState["DIR"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["DIR"];
}
set
{
ViewState["DIR"] = value;
}
}