dropdownlist disable in asp.net - c#

when admin approve/reject any document once then when admin again login then he/she not be able to approve/reject documents again and dropdownlist will be disabled only for those documents which can be once approve/reject then when admin view any new documents then drop down will be enable and when admin approve/reject this document then it will be disable dropdownlist for not approve /reject again
for this i do this
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList abc = (e.Row.FindControl("DropDownList9") as DropDownList);
abc.Enabled = false;
}
}
but this code show me all dropdownlist are disable .
any solution how i will do this?

According to your comment, I assume your DataSource is either DataTable or DataSet.
If so, you want to cast DataItem to DataRowView inside RowDataBound Event to get the value of the status column.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList runat="server" ID="DropDownList9">
<asp:ListItem Text="Approve" Value="1" />
<asp:ListItem Text="Reject" Value="2" />
<asp:ListItem Text="Pending" selected="selected" Value="3">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var table = new DataTable();
table.Columns.Add("Id", typeof (int));
table.Columns.Add("Name", typeof (string));
table.Columns.Add("ApproveID", typeof(string));
table.Rows.Add(1, "Jon Doe", "1");
table.Rows.Add(2, "Eric Newton", "2");
table.Rows.Add(3, "Marry Doe", "3");
GridView1.DataSource = table;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as DataRowView;
var dropDownList = e.Row.FindControl("DropDownList9") as DropDownList;
// Get value from ApproveID column,
// and check whehter Approve, Reject or others.
switch (item["ApproveID"].ToString())
{
case "1":
case "2":
dropDownList.Enabled = false;
break;
default:
dropDownList.Enabled = true;
break;
}
}
}

You need to access the data item from each row, I am assuming it is available on the object your are binding to the grid, and determine if they have been approved / rejected. If so then you should run you logic to disable:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var yo = (YOUR-OBJECT)e.Row.DataItem;
if(yo.Status !== null OR yo.Status != 'Not Reviewed'){
//Find the DropDownList in the Row
DropDownList abc = (e.Row.FindControl("DropDownList9")
as DropDownList);
abc.Enabled = false;
}
}
}

you can ask on which row you are with this code:
if (e.Row.RowIndex == <aRowNumber>)
{
...
}

Related

C# GridView Dynamic CheckBox Disappearing

I have a fairly simple application which returns a list of failed reports with an ID, Name and Time Bound fields and Checkbox template field on the left.
I have a 'Reschedule' button which when pressed, should pick up the rows where the checkbox has been ticked and process them.
The GridView loads up successfully and I can select/unselect the CheckBoxes but when I press the 'Reschedule' button and return to the code, the checkboxes no longer exist.
I know this is related to Dynamic Controls/Postback and that the Checkboxes need to be re-created and I've tried numerous suggestions to previous similar questions but nothing has worked
GridView - AutoGenerate Columns False (tried true)
Button - OnClientClick="" (tried return false)
The fields are initially created and bound to a data table (the data table has 3 columns mapping to the 3 Bound fields) like this:-
TemplateField tfield = new TemplateField();
failedSchedulesGridView.Columns.Add(tfield);
BoundField bfield1 = new BoundField();
bfield1.HeaderText = "SI_ID";
bfield1.DataField = "si_id";
failedSchedulesGridView.Columns.Add(bfield1);
BoundField bfield2 = new BoundField();
bfield2.HeaderText = "SI_NAME";
bfield2.DataField = "si_name";
failedSchedulesGridView.Columns.Add(bfield2);
BoundField bfield3 = new BoundField();
bfield3.HeaderText = "SI_UPDATE_TS";
bfield3.DataField = "si_update_ts";
failedSchedulesGridView.Columns.Add(bfield3);
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
Page_Load
As can be seen I've tried recreating the GridView columns here but it didn't work and is commented out
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//TemplateField tfield = new TemplateField();
//failedSchedulesGridView.Columns.Add(tfield);
//BoundField bfield1 = new BoundField();
//bfield1.HeaderText = "SI_ID";
//bfield1.DataField = "si_id";
//failedSchedulesGridView.Columns.Add(bfield1);
//BoundField bfield2 = new BoundField();
//bfield2.HeaderText = "SI_NAME";
//bfield2.DataField = "si_name";
//failedSchedulesGridView.Columns.Add(bfield2);
//BoundField bfield3 = new BoundField();
//bfield3.HeaderText = "SI_UPDATE_TS";
//bfield3.DataField = "si_update_ts";
//failedSchedulesGridView.Columns.Add(bfield3);
}
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
}
OnRowDataBound
protected void OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
cbx++;
CheckBox cb = new CheckBox();
cb.ID = "cb" + cbx;
e.Row.Cells[0].Controls.Add(cb);
}
}
The Code fails when I try to access the Checkboxes after the 'Reschedule' button is pressed because the checbox is not found :-
protected void ReschedulePB2_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in failedSchedulesGridView.Rows)
{
i++;
string cbName = "cb" + i;
CheckBox cb = (CheckBox)row.Cells[0].FindControl(cbName);
if (cb.Checked)
try this
Write this in your aspx page
<asp:GridView ID="failedSchedulesGridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" Width="850px" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:CheckBox ID="cbHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="si_id" HeaderText="SI_ID" SortExpression="si_id" />
<asp:BoundField DataField="si_name" HeaderText="SI_NAME" SortExpression="si_name" />
<asp:BoundField DataField="si_update_ts" HeaderText="SI_UPDATE_TS" SortExpression="si_update_ts" />
</Columns>
</asp:GridView>
your page load should look like this
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
}
}
your reschedule click would be
protected void ReschedulePB2_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in failedSchedulesGridView.Rows)
{
CheckBox cb = (CheckBox)row.Cells[0].FindControl("cbItem");
if (cb.Checked)

how to get dynamic check box status an asp in a gridview in asp webform?

i have a gridview in a asp.net webform and i add it a check box column like this (the dataTable first column(0) is empty in sql data source and i add check boxes on the column cells):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (rowNum != 0)//except first row
{
CheckBox cb = new CheckBox();
cb.Enabled = true;
e.Row.Cells[0].Controls.Add(cb);//row[0]=first clmn-and this event happend for all rows
}
rowNum++;
}
now i have a dynamic check box column! and user should check some of them and click the submit then i need the row number of the checked check boxes.
how can i do this?
i tried this before:
DataTable editTable = new DataTable();
editTable.Rows.Add(GridView1.Rows[0]);
var x = editTable.Rows[0][0];
but the x cannot get the check box true or false! it seems that getting me the original field under the check box content.
regards.
Instead of creating the controls dynamically which in most cases results in a lot of trouble, you could add the CheckBoxes in one or more template columns. The following sample shows how to add a checkbox in a template column and how to retrieve the value afterwards:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chb" runat="server" />
<asp:HiddenField ID="hiddenId" runat="server"
Value='<%# DataBinder.Eval(Container.DataItem, "Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Text" />
</Columns>
</asp:GridView>
In my sample, I've bound some data to the GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var dt = GetData();
gridView.DataSource = dt;
gridView.DataBind();
}
}
private DataTable GetData()
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Text", typeof(string));
for (int i = 0; i < 10; i++)
dt.Rows.Add(new object[] { i, "Test text " + i.ToString() });
return dt;
}
If you need to set the value, you can do so in the RowDatabound event. The following code shows how to retrieve the value of the Checkbox controls:
protected void btn_Click(object sender, EventArgs e)
{
List<int> checkedIds = new List<int>();
foreach(GridViewRow row in gridView.Rows.OfType<GridViewRow>()
.Where(x => x.RowType == DataControlRowType.DataRow))
{
var hiddenId = (HiddenField)row.Cells[0].FindControl("hiddenId");
var checkBox = (CheckBox) row.Cells[0].FindControl("chb");
if (checkBox.Checked)
checkedIds.Add(int.Parse(hiddenId.Value));
}
}

Access gridview rows after postback

Good day!
I need to dynamycally upload files and display information in gridview.
After file upload, i need to select file type in dropdown.
But after postback i can't access Gridview1 rows, and get selected file types. After postback Gridview1.Rows.Count = 0.
Is it possible to get selected values from DropDownLists?
<asp:GridView ID="GridView1" runat="server" ShowHeader="False" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FileName" />
<asp:TemplateField HeaderText="FileType">
<ItemTemplate>
<asp:DropDownList runat="server">
<asp:ListItem Value="Val1">Val1</asp:ListItem>
<asp:ListItem Value="Val2">Val2</asp:ListItem>
<asp:ListItem Value="Val3">Val3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField DeleteText="Remove" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:FileUpload ID="FileUpload" runat="server" onchange="this.form.submit()" />
Thanks
In Page_Load, during PostBack, GridView rows is empty.
protected void Page_Load(object sender, EventArgs e)
{
RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
}
private void AddRow(string file)
{
DataTable dt = (DataTable)Page.Session["Files"];
if (dt == null)
{
AddDataTableToSession();
dt = (DataTable)Page.Session["Files"];
}
DataRow dr = dt.NewRow();
dr["FileName"] = file;
dr["FileType"] = 0;
dt.Rows.Add(dr);
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
private void AddDataTableToSession()
{
DataTable dt = new DataTable("Files");
DataColumn dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileType", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["Files"] = dt;
}
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
int recordToDelete = e.RowIndex;
DataTable dt = (DataTable)Page.Session["Files"];
int cn = dt.Rows.Count;
dt.Rows.RemoveAt(recordToDelete);
dt.AcceptChanges();
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
Try by changing Ispostback like this.
if (!IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
(or)
if (IsPostBack == false && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
So that, if page load occurs, Your if condition will get true.
You can find the drop down list and update it with the value in the RowDataBOund event of gridview as follows
protected void Page_Load(object sender, EventArgs e)
{
//RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
else
{
AddDataTableToSession();
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
FilesGridView.RowDataBound += KBFilesGridView_RowDataBound;
}
and row databound will be as follows
void KBFilesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
DataRow dr= ((DataRowView)e.Row.DataItem).Row;
ddl.SelectedValue = dr["FileType"].ToString();
}
}
Similary you can get the value of dropdown for remove method as well as follows
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
if(ddl.SelectedValue == "someValue") doSomeThing();
}
}
}

how to delete a row from the gridview by using a button outside the gridview

This seems like a repeated question but i'm not able to get my answer.
I have a grid view and I need to delete a particular row, when I click on a button outside the gridview.
protected void btnDelete_Click(object sender, EventArgs e)
{
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[DataGV1.SelectedIndex];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
The session variable has the previous state of datatable.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
_selectedIndex = int.Parse(e.CommandArgument.ToString());
}
Gridview controls
onselectedindexchanged="DataGV1_SelectedIndexChanged"
OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
<Columns>
<asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
<asp:BoundField DataField="role" HeaderText="role" HeaderText="Frist_name"
SortExpression="first_name" Text="First_name" />
</Columns>
</asp:GridView>
This doesn't seem to work.
Can u please tell me where I am going wrong?
If button is outside the GridView then no need to handle RowCommand event (In fact it is inappropriate).
Suggestion:
You have to add a TemplateField column, drop the CheckBox control in ItemTemplate of TemplateField and write code in click handler of button to traverse the GridView.Rows collection, identify the selected row by reading value of CheckBox control and perform deletion action if that CheckBox is checked.
Demo DataSource (List<T>)
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Item> Data()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
return list;
}
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />
Code-behind (Page_Load)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = Item.Data();
GridView1.DataSource = Session["data"];
GridView1.DataBind();
}
/*--- RowCommand handler ---*/
GridView1.RowCommand += (sa, ea) =>
{
ViewState["RowIndex"] = ea.CommandArgument.ToString();
};
/*--- Delete button click handler ---*/
btnDelete.Click += (sa, ea) =>
{
if (ViewState["RowIndex"] != null)
{
int index = int.Parse(ViewState["RowIndex"].ToString());
List<Item> items = Session["data"] as List<Item>;
items.RemoveAt(index);
GridView1.DataSource = Session["data"];
GridView1.DataBind();
ViewState["RowIndex"] = null;
}
};
}
You have to store the _selectedIndex in a ViewState, and then on delete button click you retrieve the _selectedIndex from the Viewstate and use that to delete the row from your dataset, and reload the grid.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
ViewState["SelIndex"] = e.CommandArgument.ToString();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if(ViewState["SelIndex"] == null)
return;
int selIndex = int.Parse(ViewState["SelIndex"]);
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[selIndex ];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
take a look at these articles that would explain to delete a single/multiple rows from gridview.
http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/
http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/

Reference ImageButton in asp.net

I have a GridView with two columns that have capability to be sorted. After its sorted I want to display an image next to a column with Arrow pointing up or down for Asc and Desc sort.
I cannot figure out how to reference an ImageButton object so I can set the ImageButton.ImageUrl to an actual image based on if its Asc and Desc.
Here is my .aspx code:
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="Name_SortLnkBtn" runat="server" Text="Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="Name" CausesValidation="false" />
<asp:ImageButton ID="Name_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="Name" CausesValidation="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/TestResults/Diabetes.aspx?ID="+Eval("ID") %>'><%#Eval("Name")%></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="HouseName_SortLnkBtn" runat="server" Text="House Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="House" CausesValidation="false" />
<asp:ImageButton ID="HouseName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="House" CausesValidation="false" />
</HeaderTemplate>
<ItemTemplate><%#Eval("House")%></ItemTemplate>
</asp:TemplateField>
</Columns>
Help would be great appreciated.
Updated .aspx.cs file:
public partial class Home : System.Web.UI.Page
{
protected _code.SearchSelection _SearchSelection = new _code.SearchSelection();
protected _code.Utils _utils = new _code.Utils();
protected ImageButton sortImage = new ImageButton();
protected void Page_Load(object sender, EventArgs e) {
//if (!IsPostBack) {
Master.FindControl("Home").ID = "active";
GridView1_DataBind();
//Guid ID = new Guid(_SearchSelection.getUserID().Tables[0].Rows[0]["u_ID"].ToString());
//}
}
protected void GridView1_DataBind() {
string selection = string.Empty;
TreeView treeMain = (TreeView)tree.FindControl("treeMain");
if (treeMain.SelectedNode != null)
selection = treeMain.SelectedNode.Text;
else
selection = Session["Selection"].ToString();
DataSet mainData = _utils.getStoreProcedure(new SqlParameter[] { new SqlParameter("#Selection", selection) }, "sp_getTenantsWithDiabetes", ConfigurationManager.ConnectionStrings["TIPS4"].ConnectionString);
Session["MainData"] = mainData.Tables[0];
GridView1.DataSource = mainData.Tables[0];
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
//Retrieve the table from the session object.
DataTable dt = Session["MainData"] as DataTable;
ImageButton imageButton = new ImageButton();
if (dt != null) {
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
//imageButton.ImageUrl = "~/App_Themes/Sugar2006/Images/arrow_up.gif";
//imageButton.Visible = true;
this.GridView1.DataSource = Session["MainData"];
this.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;
}
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
var imageButton = (ImageButton)e.Row.FindControl("Name_SortImgBtn");
sortImage = imageButton;
//imageButton.ImageUrl = "~/App_Themes/Sugar2006/Images/arrow_up.gif";
//imageButton.Visible = true;
}
}
To get a reference to the ImageButton defined in your HeaderTemplate, you can wire up the RowDataBound event of the GridView. In the event handler, check if the row is the header row by using the RowType property, and then use the FindControl method to get a reference to the control.
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Header)
{
var imageButton = (ImageButton)e.Row.FindControl("Name_SortImgBtn");
imageButton.ImageUrl = "~/myimage.gif";
}
}
EDIT
I think you're on the right track. I would make the following changes:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["MainData"] as DataTable;
if (dt == null) return;
//Sort the data
dt.DefaultView.Sort = e.SortExpression + " " +
GetSortDirection(e.SortExpression);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
There's no need to worry about the ImageButton in the Sorting event handler. The click of the LinkButton in the header will cause a post back, and the Sorting event handler will be called. It will run before the RowDataBound event is triggered (that won't happen until the GridView1.DataBind method is called). Also, the GetSortDirection method will store the sort expression and the sort order in the ViewState. We'll need those values later in the RowDataBound event handler (shown below).
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Determine sort column and sort order
var column = ViewState["SortExpression"] != null ?
ViewState["SortExpression"].ToString() : string.Empty;
var sortDirection = ViewState["SortDirection"] != null ?
ViewState["SortDirection"].ToString() : string.Empty;
//Find ImageButton based on sort column (return if not found)
var imageButtonID = string.Concat(column, "_SortImgBtn");
var imageButton = e.Row.FindControl(imageButtonID) as ImageButton;
if(imageButton == null) return;
//Determine sort image to display
imageButton.ImageUrl = string.Equals("asc", sortDirection.ToLower()) ?
"~/App_Themes/Sugar2006/Images/arrow_up.gif" :
"~/App_Themes/Sugar2006/Images/arrow_down.gif";
imageButton.Visible = true;
}
}
In this event handler, we'll retrieve the values stored in the ViewState to determine which ImageButton to make Visible and which image url to use based on the sort direction. I made the assumption that you have given the ImageButton controls an ID of the column name plus "_SortImgBtn" (if you do things in this manner you can avoid a switch statement to map the column to the control name). Just make sure that the ImageButton controls have Visible set to false in the front page and the sorting image should be displayed.

Categories