About Me

My photo
"O Allah, make my love for You the most beloved thing to me, and my fear for You the most fearful thing to me, and remove from me all worldly needs and wants by instilling a passion for meeting You, and when You have given the people of the world the pleasures of their world, make the coolness of my eyes (pleasure) in worshipping You." Ameen

Tuesday, July 3, 2007

Obtaining values from a hidden column in a grid view

Although in .NET 2003, accessing a hidden cell in a grid was pretty straight forward, with 2005, a bit of a work-around is required in order to achieve the same. Although ‘Visible=False’ would allow us to access a cell for a hidden column in 2003, in the case of 2005, we need to use the style ‘display:none;’ in order to achieve the same. A simple example is as given below.










Applying it to hide the column in the grid,




Wednesday, June 27, 2007

Checking All Pages in a GRID - ASP.NET

Checking All Pages in a GRID - ASP.NET

This article explains how to maintain the selected checkboxes across pages and also through sorting. I have referred many resources on the net in developing this code. It’s quite a simple code at the end of the day, although I did spend sometime figuring it out at the beginning.

Download Code

References

The following article forms the basis of what I have done here. Instead of the “Data Keys” used here I am using the unique “rowno” for each record.

http://aspalliance.com/774

Why couldn’t I use the code in the above article in my application?

The above application uses the primary key value in order to uniquely identify each record, but in the case of my application (i.e. my real world app,not the sample here) which queried many tables I couldn’t find a key which was unique to the entire rowset. So I thought it was ideal to use the row index. So I have modified the application to cater for this requirement. The rest is more or less identical to the above article.

Anyway let me explain!

The grid in this article enables us to select records in the current page and also to select all records in the grid as depicted below.


Data extraction code
The following code snippets demonstrate the data retrieval code for this application. I’m using a session variable in order to eliminate server trips to the db server.

The dataset is stored in a session variable and handled across by using a static dataset.

private DataSet getProductData()
{
try
{
string strqry = "select ProductID,ProductName,SupplierID,CategoryID,UnitPrice from Products";


SqlConnection con = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(strqry, con);
DataSet ds = new DataSet();
da.Fill(ds, "Products");
return ds;
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
return null;
}
}


private void getData()
{
try
{

if (Session["ProductList"] == null)
{
dsProducts = getProductData();
DataColumn dc = new DataColumn("rowno", System.Type.GetType("System.Int32"));
dsProducts.Tables[0].Columns.Add(dc);

int I = 0;

foreach (DataRow r in dsProducts.Tables[0].Rows)
{
r[dsProducts.Tables[0].Columns.Count - 1] = I;
I += 1;
}

Session["ProductList"] = dsProducts;
GridView1.PageIndex = 0;
}
else
{
dsProducts = (DataSet)Session["ProductList"];
}

DataTable dt = dsProducts.Tables[0];

DataView dv = new DataView(dt);


string SortField = (ViewState["SortOrder"] == null) ? "" : ViewState["SortOrder"].ToString();
// set the default sort order
if (SortField == "")
SortField = "ProductID asc";

dv.Sort = SortField;

GridView1.DataSource = dv;
GridView1.DataBind();


}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
}



As you might see in this code I’m creating a new data column named “rowno”, and assigning it with the row index value for each record, which undoubtedly is unique across this dataset.


DataColumn dc = new DataColumn("rowno", System.Type.GetType("System.Int32"));

dsProducts.Tables[0].Columns.Add(dc);

int I = 0;

foreach (DataRow r in dsProducts.Tables[0].Rows)
{
r[dsProducts.Tables[0].Columns.Count - 1] = I;
I += 1;
}

(The following functions are from the article mentioned above; I have modified it to cater for my requirement)


The “RememberOldValues()” method uses an Array list by the way of a session to remember the selected values throughout the application. Here I’m checking to see whether the “select entire grid” check box is selected, if so I will be using the dataset to get all the values or else I will be checking the current data grid page to get the selected values while preserving the formerly selected values.

private void RememberOldValues()
{

ArrayList categoryIDList = new ArrayList();
int index = -1;

HtmlInputCheckBox cbHeaderAllPages = (HtmlInputCheckBox)GridView1.HeaderRow.FindControl("checkAllPages");

if (((cbHeaderAllPages != null) & (cbHeaderAllPages.Checked)))
{
DataTable dt = dsProducts.Tables[0];

foreach (DataRow di in dt.Rows)
{

index = (int)di[dt.Columns.Count - 1];

// Check in the Session
if ((Session["CHECKED_ITEMS"] != null))
{
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
}

if (!categoryIDList.Contains(index))
{
categoryIDList.Add(index);
}

}
}
else
{

foreach (GridViewRow di in GridView1.Rows)
{


index = Int32.Parse(di.Cells[di.Cells.Count - 1].Text);

bool result = ((HtmlInputCheckBox)di.FindControl("pId")).Checked;

// Check in the Session
if ((Session["CHECKED_ITEMS"] != null))
{
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
}

if (result)
{
//Response.Write(index.ToString());
if (!categoryIDList.Contains(index))
{
categoryIDList.Add(index);
}
}
else
{
categoryIDList.Remove(index);
}

}
}

if (((categoryIDList != null) & categoryIDList.Count > 0))
{
Session["CHECKED_ITEMS"] = categoryIDList;
}


}


By using the following function you may populate the data grid with the formerly selected rows.


private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];

if (((categoryIDList != null)))
{

if (categoryIDList.Count > 0)
{
foreach (GridViewRow di in GridView1.Rows)
{
int index = Int32.Parse(di.Cells[di.Cells.Count - 1].Text);
if (categoryIDList.Contains(index))
{
HtmlInputCheckBox myCheckBox = (HtmlInputCheckBox)di.FindControl("pId");
myCheckBox.Checked = true;
}
}
}

}

}


The above functions can be called in the “pageindexchanging” and “sort” as shown events in order to achieve the desired results.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
GridView1.PageIndex = e.NewPageIndex;
getData ();
RePopulateValues();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
RememberOldValues();
GridView1.PageIndex = 0;

string strSort = "";
//get the existing sort cookie
HttpCookie objCookieExisting = Request.Cookies["SortOrder"];
if (objCookieExisting != null)
strSort = objCookieExisting.Value.ToString();

//set so it does a descending order first
if (strSort == e.SortExpression + " Desc")
strSort = e.SortExpression + " Asc";
else
strSort = e.SortExpression + " Desc";

ViewState["SortOrder"] = strSort;
//'write the sort information to a cookie
HttpCookie objCookie = new HttpCookie("SortOrder", strSort);
objCookie.Expires = DateTime.Today.AddYears(1);
Response.Cookies.Add(objCookie);

getData();
RePopulateValues();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
}



I hope whoever hits this page will find this code useful. All comments, suggestions and improvements are most welcome. I like to improve through my mistakes whether it is life or coding, so please feel free to criticize my work.

Many Thanks,
Mifla