GridView Sorting in ASP.NET 2 using C# - c#

I need GridView Sorting in ASP.NET 2 using C# and tried this tutorial:
http://www.dotnetfox.com/articles/gridview-sorting-example-in-Asp-Net-using-C-Sharp-1082.aspx
Below is my code C# net 2 for sorting column in GridView but I've this error:
Exception Details: System.IndexOutOfRangeException: Cannot find table 0.
in this line why?
Line 39: GridViewBind();
Line 40: DataTable dt = new DataTable();
Line 41: dt = ds.Tables[0];
Line 42: {
Line 43: string SortDir = string.Empty;
DataSet ds = new DataSet();
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void gvEmployee_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewBind();
DataTable dt = new DataTable();
dt = ds.Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
public void GridViewBind()
{
SQL = " SELECT * FROM doTable; ";
try
{
conn.Open();
dadapter = new OdbcDataAdapter(SQL, conn);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
}
catch (Exception ee)
{
throw ee;
}
finally
{
conn.Close();
conn.Dispose();
}
}
EDIT 1
using System;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Av_Default : System.Web.UI.Page
{
OdbcConnection conn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
string SQL;
OdbcDataAdapter dadapter;
DataSet dset;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void gvEmployee_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewBind();
DataTable dt = new DataTable();
dt = ds.Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
public void GridViewBind()
{
SQL = " SELECT * FROM doTAble; ";
try
{
conn.Open();
dadapter = new OdbcDataAdapter(SQL, conn);
dset = new DataSet();
dset.Clear();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
}
catch (Exception ee)
{
throw ee;
}
finally
{
conn.Close();
conn.Dispose();
}
}

protected void gvEmployee_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GetRows();
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
public void GridViewBind(DataTable dt){
GridView1.DataSource=dt;
GridView1.DataBind();
}
public DataTable GetRows()
{
var SQL = " SELECT * FROM doTAble; ";
//You should use the "using" resource acquisition statement
// http://www.dotnetperls.com/sqlconnection
using(var conn=new OdbcConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString))
{
conn.Open();
var dadapter = new OdbcDataAdapter(SQL, conn);
var dset = new DataSet();
dadapter.Fill(dset);
return dset.Tables[0];
}
}

Related

How do I make paging gridview that is bound to dataset on dropdwon list change event?

I am binding the gridview from sqlserver using dataset and datable on PageLoad.
public DataSet Ds
{
get
{
object temp = ViewState["Ds"];
return temp == null ? null : temp as DataSet;
}
set
{
ViewState["Ds"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridCustAllInfoBind();
}
}
public void gridCustAllInfoBind()
{
try
{
//open the db connection if it is closed...
if (connection.State == ConnectionState.Closed)
connection.Open();
command = new SqlCommand();
command.CommandText = "Z_cust";
command.CommandType = CommandType.StoredProcedure;
command.Connection = connection;
SqlDataAdapter daAcc = new SqlDataAdapter(command);
this.Ds = new DataSet();
daAcc.Fill(Ds);
if (Ds.Tables[0].Rows.Count == 0)
{
Ds.Tables[0].Rows.Add(Ds.Tables[0].NewRow());
gridCustomer.DataSource = Ds;
gridCustomer.DataBind();
int columncount = gridCustomer.Rows[0].Cells.Count;
gridCustomer.Rows[0].Cells.Clear();
gridCustomer.Rows[0].Cells.Add(new TableCell());
gridCustomer.Rows[0].Cells[0].ColumnSpan = columncount;
gridCustomer.Rows[0].Cells[0].Text = "No Records Found";
}
else
{
//gridCustomer.DataSource = idr;
gridCustomer.DataSource = Ds;
gridCustomer.DataBind();
}
}
catch (Exception ex)
{
lblMessagePaySerach.Text= ex.Message;
}
finally //Close db Connection if it is open....
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
Here I am filtering the dataset on demand, then bind the gridview to it.
protected void btnSearchCust_Click(object sender, EventArgs e)
{
if (ddlStatus.SelectedIndex == 0 && ddlColumns.SelectedIndex == 0)
{
var strExpr = "Status='Active'";
var dv = Ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
gridCustomer.DataSource = newDS;
int size = int.Parse(ddlPaging.SelectedItem.Value.ToString());
gridCustomer.PageSize = size;
gridCustomer.DataBind();
}
}
Here I am selecting dropdownlist values, then I have to show gridview records on demand.
protected void ddlPaging_SelectedIndexChanged(object sender, EventArgs e)
{
int size = int.Parse(ddlPaging.SelectedItem.Value.ToString());
gridCustomer.PageSize = size;
btnSearchCust_Click(sender, e);
}

Manual Grid View Sorting

My Grid View is manually data bound (for other things to work). Reading other threads I have to manage my own sorting events.
When clicking a column to sort it on my webpage I get the error:
"Object reference not set to an instance of an object."
The result of this was that table was null, but I cannot see why it is null.
Any ideas?
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable table = GetData();
table.DefaultView.Sort = e.SortExpression + " " + SetSortDirection(e.SortDirection.ToString());
GridView1.DataSource = table;
GridView1.DataBind();
}
.
protected string SetSortDirection(string currentsortDirection)
{
string sortDirection;
if (currentsortDirection == "Ascending")
{
sortDirection = "Descending";
}
else
{
sortDirection = "Ascending";
}
return sortDirection;
}
EDIT:
public DataTable GetData()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True");
conn.Open();
string query = "SELECT * FROM tablex WHERE Property='" + Request.QueryString["xxx"] + "'";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
Thanks.
DataTable table = BuildInfo_GridView.DataSource as DataTable;
like this u won't get the datasource what u already binded call back end query to get tha datatable or when u r binding the data only store it in view state and get it
Save your sort order in view state
if (ViewState["sortOrder"] != null)
{
ViewState["sortExpression"] = e.SortExpression;
if (ViewState["sortOrder"].ToString().ToUpper() == "ASCENDING")
{
e.SortDirection = SortDirection.Descending;
ViewState["sortOrder"] = SortDirection.Descending.ToString();
}
else
{
e.SortDirection = SortDirection.Ascending;
ViewState["sortOrder"] = SortDirection.Ascending.ToString();
}
}
else
{
ViewState["sortExpression"] = e.SortExpression;
ViewState["sortOrder"] = e.SortDirection.ToString();
}

no row at position 0

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

How to filter gridview from textbox?

I need to filter a gridview that retreives filtered data from a table. Therefore I bound the gridview to a dataset. Now i can't seem to find a solution to filter it further.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//need to insert code here for filtering GridView1 based on TextBox1.Text
}
Thanks for the help.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection myCon = new SqlConnection(connectionstring);
SqlDataAdapter adapter = new SqlDataAdapter(cmd, myCon);
adapter.Fill(ds);
DataView view = new DataView();
view.Table = ds.Tables[0];
view.RowFilter = "ColumnName = " + TextBox1.Text.Trim();
GridView1.DataSource = view;
GridView1.DataBind();
}
you have to refactor your code.
Here's a complete sample which handles GridView's paging, sorting(both directions) and filtering(two columns).
// store sorting across postbacks in a ViewState variable
public string SortExpression
{
get
{
if (ViewState["GridSort"]== null)
{
ViewState["GridSort"] = "Column1 ASC";
}
return ViewState["GridSort"].ToString();
}
set { ViewState["GridSort"] = value; }
}
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
Here's the main method that does all (including the filter-function):
private void BindGrid()
{
try
{
var tblData = new DataTable();
var filter1 = TextBox1.Text.Trim();
var filter2 = TextBox2.Text.Trim();
using (var sqlCon = new System.Data.SqlClient.SqlConnection(connectionstring))
{
String sql = String.Empty;
var sqlCmd = new System.Data.SqlClient.SqlCommand();
if (filter1.Length != 0 && filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 AND Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else if (filter1.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column1 LIKE #Column1 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column1", string.Format("%{0}%", filter1));
}
else if (filter2.Length != 0)
{
sql = "SELECT Column1,Column2 FROM Table WHERE Column2 LIKE #Column2 ORDER BY {0}";
sqlCmd.Parameters.AddWithValue("#Column2", string.Format("%{0}%", filter2));
}
else
{
// no filter, select all
sql = "SELECT Column1,Column2 FROM Table ORDER BY {0}";
}
sqlCmd.CommandText = string.Format(sql, this.SortExpression);
sqlCmd.Connection = sqlCon;
using (System.Data.SqlClient.SqlDataAdapter objAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlCmd))
{
objAdapter.Fill(tblData);
}
}
GridView1.DataSource = tblData;
GridView1.DataBind();
}
catch (Exception)
{
// log
throw;
}
}
Paging:
private void GridView1_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
Filter-Button-Click:
private void BtnFilter_Click(object sender, System.EventArgs e)
{
BindGrid();
}
Sorting:
protected void GridView1_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
string currentSortColumn = null;
string currentSortDirection = null;
currentSortColumn = this.SortExpression.Split(' ')[0];
currentSortDirection = this.SortExpression.Split(' ')[1];
if (e.SortExpression.Equals(currentSortColumn))
{
//switch sort direction
switch (currentSortDirection.ToUpper())
{
case "ASC":
this.SortExpression = currentSortColumn + " DESC";
break;
case "DESC":
this.SortExpression = currentSortColumn + " ASC";
break;
}
}
else
{
this.SortExpression = e.SortExpression + " ASC";
}
BindGrid();
}
Just converted from VB manually, so i hope there are no remaining errors.
sql = new SqlConnection(Connection.con);
adapter = new SqlDataAdapter(#"select EntryID * from Table where Name like #Name ", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;

Sorting in gridview is not working

I am trying Sorting functionality in Grid view but its not working.Can some body help?
Code:
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dv = new DataView(dt);
dv.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dv;
GridView1.DataBind();
}
Here dt is coming null.why? pls help thanks.
EDIT:
enter code here <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="true" AllowSorting="true" PageSize="12"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting">
EDIT(Total code)
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
DataSet ds;
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected DataSet FillDataSet()
{
string source = "Database=GridTest;Server=Localhost;Trusted_Connection=yes";
con = new SqlConnection(source);
cmd = new SqlCommand("proc_mygrid", con);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
return ds;
}
protected void GetValues(object sender, EventArgs e)
{
FillDataSet();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
int newPagenumber = e.NewPageIndex;
GridView1.PageIndex = newPagenumber;
GridView1.DataSource = FillDataSet();
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet ds = FillDataSet();
DataTable dt = ds.Tables[0];
if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dt;
GridView1.DataBind();
}
CODE:
private string GetSortDirection(string column)
{
string sortDirection = "DESC";
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "DESC"))
{
sortDirection = "ASC";
}
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Because you're setting a DataSet as DataSource and then casting it to DataTable with the operator as.
The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.
If you only have one datatable in your dataset then you can get the first element like this:
ds.Tables[0];
... or use the name of the table:
ds.Tables["myTable"];
in your case you can try...
DataTable dt = GridView1.DataSource.Tables[0] as DataTable;
Hope it helps!
EDIT:
with regards to your sorting problem (once you get the datatable):
if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataBind();
}
You can do this because dt is a reference to the exact same object that's already set as DataSource for your grid. It should do the trick - if not there's smt else I am missing (such as we're sorting the wrong table meaning you have more than one table in the DataSet).
EDIT:
had a look at your code. I don't know exactly when GetValues gets fired but I suspect it's causing your problem (I think it might be overriding your sorting or smt along those lines).
If you comment out FillDataSource from getValues and modify your PageLoad to do this:
void Page_Load(Object sender, EventArgs e)
{
// Load data only once, when the page is first loaded.
if (!IsPostBack)
{
Session["myDataSet"] = FillDataSet();
}
}
then in your sort method you retrieve the DataSource like this:
DataTable dt = ((DataSet)Session["myDataSet"]).Tables[0];
Also you can retrieve the DataSet from session in your pagination handler method.
You should also notice an improvement in performance since you're retrieving the stuff form the db just once.
Give it a shot!
In Testing.aspx.cs
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (dataset != null)
{
datatable = dataset.Tables[0];
DataView dataView = new DataView(datatable);
dataView.Sort = e.SortExpression;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
In Testing.aspx
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True" OnSorting="GridView1_Sorting">

Categories

Resources