Variables lost on postback in asp.net - c#

I have a gridview with some data and I want to add a checkbox column which can choose multiple rows. By clicking on it I want to save an primary key of row and change css class of row.
Using this article(step 2) I created itemtemplate,added there a checkbox(specifying ID as TransactionSelector), and add a checkedChange() to it. There I only change a css class of row and add a row index to arraylist. But when I click button with event which show this list, it has no items.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="TransactionSelector" runat="server"
oncheckedchanged="TransactionSelector_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="iTransactionsId" HeaderText="iTransactionsId"
SortExpression="iTransactionsId" />
<asp:BoundField DataField="mAmount" HeaderText="mAmount"
SortExpression="mAmount" />
<asp:BoundField DataField="vchTransactionType" HeaderText="vchTransactionType"
SortExpression="vchTransactionType" />
<asp:BoundField DataField="dtDate" HeaderText="dtDate"
SortExpression="dtDate" />
<asp:BoundField DataField="cStatus" HeaderText="cStatus"
SortExpression="cStatus" />
<asp:BoundField DataField="test123" HeaderText="test123"
SortExpression="test123" />
</Columns>
<RowStyle CssClass="unselectedRow" />
</asp:GridView>
</asp:Panel>
<asp:Panel ID="InfoPanel" runat="server" CssClass="infoPanel">
<asp:Button ID="ShowSelected" runat="server" Text="Button"
onclick="ShowSelected_Click" />
<asp:Label ID="InfoLabel" runat="server"></asp:Label>
</asp:Panel>
C Sharp code:
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList indices = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void TransactionSelector_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
// row.CssClass = (cb.Checked) ? "selectedRow" : "unselectedRow";
if (cb.Checked)
{
row.CssClass = "selectedRow";
indices.Add(row.RowIndex);
}
else
{
row.CssClass = "unselectedRow";
indices.Remove(row.RowIndex);
}
}
protected void ShowSelected_Click(object sender, EventArgs e)
{
InfoLabel.Text = "";
foreach (int i in indices)
{
InfoLabel.Text += i.ToString() + "<br>";
}
}
}
}

You have to persist variable in postback using ViewState. Also its better if you use List<T> generic implementation rather than ArrayList
ViewState["Indices"] = indices;
And to recover it back
indices = ViewState["Indices"] as ArrayList;

As Habib said, you could use ViewState. You could also use ControlState instead, as shown here. If your code is in a custom control or user control, you may also need to override OnInit to
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
Please feel free to respond with feedback. I'm new at posting answers.

Related

First Click on ASP.NET control does not fire on click event

I'm seeing this behavior on two of my pages, but I'm just going to ask about the one that's more important to me at the moment. I have a page that loads information from a database into a ASP gridview and then allows the user to add a detail to each populated line.
The issue I'm having is that when the 'Edit' button of the gridview and then subsequently the 'Update' or 'Cancel' button, it takes two click to actually fire the onclick event. A post back does take place on the first click, but nothing actually happens.
I'm including the code that seems relevant below. The page uses a master page and there are a number of divs involved with formatting, I'm excluding those.
Gridview and related controls:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Text="Plant Selector: " runat="server" />
<asp:DropDownList ID="ddlPlant" OnSelectedIndexChanged="ddlPlant_SelectedIndexChanged" runat="server" />
<asp:Button ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click" runat="server" />
<p />
<asp:Label ID="lblTest" Text="" runat="server" />
<asp:Label ID="lblerror" Text="" ForeColor="Red" runat="server" />
<asp:GridView ID="gridview1" AutoGenerateColumns="false" runat="server" OnRowEditing="gridview1_RowEditing" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowUpdating="gridview1_RowUpdating">
<Columns>
<asp:BoundField DataField="JobNum" HeaderText="Job Number" ReadOnly="true" />
<asp:BoundField DataField="ModelNum" HeaderText="Model" ReadOnly="true" />
<asp:BoundField DataField="Customer" HeaderText="Customer" ReadOnly="true" />
<asp:BoundField DataField="SchCompDate" HeaderText="Sch Comp Date" ReadOnly="true" />
<asp:TemplateField HeaderText="Details">
<EditItemTemplate>
<asp:TextBox ID="Txt" Width="98%" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label Text="Click Edit to add details of exception." runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gridview1" />
</Triggers>
</asp:UpdatePanel>
Sample image below:
Here is the code behind:
private string Plant { get; set; }
// This sets the default plant based off IP.
protected void Page_PreInit(Object sender, EventArgs e)
{
getPlantFromIP();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDDL();
BindData();
}
else
{
Plant = ddlPlant.SelectedValue.ToString();
}
}
// Populates the drop down.
private void populateDDL()
{
ddlPlant.Items.Add("NC");
ddlPlant.Items.Add("WA");
setPlantInDDL();
}
private void setPlantInDDL()
{
if(Plant == "WA")
{
ddlPlant.SelectedIndex = 1;
}
if (Plant == "NC")
{
ddlPlant.SelectedIndex = 0;
}
}
private void getPlantFromIP()
{
if (Request.ServerVariables["REMOTE_ADDR"] == "70.103.118.100")
{
Plant = "WA";
//ddlPlant.SelectedIndex = 1;
}
else
{
Plant = "NC";
//ddlPlant.SelectedIndex = 0;
}
}
// Database Query.
private DataTable getDataFromDatabase()
{
DataTable rTable = new DataTable();
string plant = ddlPlant.SelectedValue.ToString();
using (var conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["workorderConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
try
{
cmd.CommandText = #"SELECT * FROM reportdatatables.compliance_exception_report
WHERE ExceptionNoted = '0' AND Plant = #plant";
cmd.Parameters.AddWithValue("#plant", plant);
MySqlDataReader reader = cmd.ExecuteReader();
rTable.Load(reader);
reader.Close();
cmd.Dispose();
}
catch
{
}
finally
{
conn.Close();
}
}
}
return rTable;
}
// Binds the data from the database to the gridview.
private void BindData()
{
DataTable data = getDataFromDatabase().Copy();
gridview1.DataSource = data;
gridview1.DataBind();
}
protected void ddlPlant_SelectedIndexChanged(object sender, EventArgs e)
{
//Plant = ddlPlant.SelectedValue.ToString();
BindData();
}
// On edit call.
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
// On cancel call.
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
}
protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
BindData();
}
Here's what I've tried:
-A lot of posts a read saw this behavior relating to autopostback settings of controls. As you can see I'm made sure to not have any control with the autopostback set to true.
-I had some concern that the behavior might be related to the updatepanel, but removing it doesn't change the behavior at all.
-I read that having AutoEventWireup="true" in your page tag can cause this. I DO have that in my page tag, but setting it to false does not fix the issue and prevents my dropdown from being populated on page load.
-There was another post that suggested the ID of the control could be changing between page load and post back. I monitored the IDs of those controls and I do not see any change in their ID.
So all that being said, I'm hoping someone has a clue as to what I'm missing. If there is any more information I can provide that might help, please let me know.
Thank you in advance.
Try this, which will make the grid editable
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
for cancel also
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
BindData();
}

Row Deleting event of a child gridview throwing exception in asp.net C#

I have searched a lot but couldn't find a solution to my problem.
With C#.Net, Asp.net 3.5 I have a 2 gridview controls in master child relation as following:
<asp:GridView ID="gridViewExistingSchedules"
runat="server" DataKeyNames="SchedulerId"
AutoGenerateColumns="false"
OnRowDataBound="gridViewExistingSchedules_RowDataBound"
OnRowCommand="gridViewExistingSchedules_RowCommand"
OnRowDeleting="gridViewExistingSchedules_RowDeleting">
<Columns>
<asp:TemplateField ItemStyle-Width="20px">
<ItemTemplate>
<asp:GridView
ID="gridViewSchedulerDetails"
runat="server"
AutoGenerateColumns="false"
DataKeyNames="SchedulerId">
<Columns>
<asp:BoundField DataField="DetailId" Visible="false" />
<asp:BoundField DataField="Survey" HeaderText="Survey" />
<asp:BoundField DataField="TimeDescription" HeaderText="Time" />
<asp:BoundField DataField="FromDate" HeaderText="From Date" />
<asp:BoundField DataField="ToDate" HeaderText="To Date" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgDelete" CommandArgument='<%# Bind("SchedulerId")%>' CommandName="Delete"
runat="server" ImageUrl="~/images/delete1.png" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgEdit" CommandArgument='<%# Bind("SchedulerId")%>' CommandName="Edit"
runat="server" ImageUrl="~/images/edit.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
<ItemStyle Width="20px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="Frequency" HeaderText="Frequency" />
<asp:BoundField DataField="DayOfWeek" HeaderText="Day Of Week" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:BoundField DataField="NextRunOn" HeaderText="Next Run On" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgDelete" CommandArgument='<%# Bind("SchedulerId")%>' CommandName="Delete"
runat="server" ImageUrl="~/images/delete.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Parent/master gridview "gridViewExistingSchedules" displays scheduled items where as child gridview "gridViewSchedulerDetails" displays details of a scheduled item (like which items were scheduled etc.)
I want to add a functionality, where a row in detailed gridview (i.e. gridViewSchedulerDetails can be deleted/edited. I have following code which handles row_deleting and row_command events:
protected void gridViewExistingSchedules_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int schedulerId = int.Parse(this.gridViewExistingSchedules.DataKeys[e.Row.RowIndex].Value.ToString());
GridView gvDetails = e.Row.FindControl("gridViewSchedulerDetails") as GridView;
gvDetails.RowCommand += new GridViewCommandEventHandler(gvDetails_RowCommand);
gvDetails.RowDeleting += new GridViewDeleteEventHandler(gvDetails_RowDeleting);
UICaller caller = new UICaller();
gvDetails.DataSource = caller.BindSchedulerDetails(schedulerId);
gvDetails.DataBind();
}
}
void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
UIWriter writer = new UIWriter();
if (e.CommandName.Equals("Delete"))
{
int surveyDetailId = int.Parse(e.CommandArgument.ToString());
if (writer.RemoveSurvey(surveyDetailId))
{
this.labelUserNotification.Text = "Deleted successfully";
}
else
this.labelUserNotification.Text = "Due to some internal error, selected item cannot be deleted";
//bind existing scheduler
UICaller caller = new UICaller();
this.gridViewExistingSchedules.DataSource = caller.BindScheduler();
this.gridViewExistingSchedules.DataBind();
}
else if (e.CommandName.Equals("Edit"))
{
}
}
void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
With above given code there is run time exception:
"The GridView 'gridViewSchedulerDetails' fired event RowDeleting which wasn't handled."
First I thought that since being in parent/child relation master gridview need to handle the row_command event of child "gridViewSchedulerDetails" so I changed the code to:
void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void gridViewExistingSchedules_RowCommand(object sender, GridViewCommandEventArgs e)
{
UIWriter writer = new UIWriter();
if (e.CommandName.Equals("Delete"))
{
int surveyDetailId = int.Parse(e.CommandArgument.ToString());
if (writer.RemoveSurvey(surveyDetailId))
{
this.labelUserNotification.Text = "Deleted successfully";
}
else
this.labelUserNotification.Text = "Due to some internal error, selected item cannot be deleted";
//bind existing scheduler
UICaller caller = new UICaller();
this.gridViewExistingSchedules.DataSource = caller.BindScheduler();
this.gridViewExistingSchedules.DataBind();
}
else if (e.CommandName.Equals("Edit"))
{
}
}
protected void gridViewExistingSchedules_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
But I am still getting same error given above.
Please advise how can I handle child gridview row delete even and what is actually happening here
You have specified that deleting event in your aspx code and that event handler is not there in your .cs file code that's why it creating problem. Either write a event handler like following.
void gridViewExistingSchedules_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
or remove following from your aspx code if you don't need that.
OnRowDeleting="gridViewExistingSchedules_RowDeleting"
Couple of things...
If you specify OnRowCommand="gridViewExistingSchedules_RowCommand" then technically this will catch the delete command too. therefore you can remove OnRowDeleting="gridViewExistingSchedules_RowDeleting" and catch it using a switch on command name. (see here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand%28v=vs.110%29.aspx)
That aside lets move on to the error.
The GridView 'gridViewSchedulerDetails' fired event RowDeleting which wasn't handled.
You are receiving this because the delete method is called on the gridview gridViewSchedulerDetails which is not being dealt with. You have 2 options to get rid of it.
Add an OnRowDeleting method to the child grid (gridViewSchedulerDetails) and handle that.
Add an OnRowCommand method to the child grid (gridViewSchedulerDetails) and handle that.
UPDATE
Just thought your image buttons contain the command name delete and edit... these are reserved for the events delete and edit and fire them respectively. As you are assigning different events in your databound this might be causing a conflict. Try changing the CommandName on your image buttons to del and ed in your child grid view and see if that helps.

Dynamic control Viewstate

I am now stuck. After spending ages trying to maintain dynamically added linkbutton or label to a gridview it seems I am overwriting a checkbox state on post back.
As stated I am dynamically adding either a linkbutton or a label to a place holder in a gridview with the following:
protected void LedgerGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
if (items[index].noteID > 0)
{
PlaceHolder label = (PlaceHolder)e.Row.FindControl("HasPrevious");
LinkButton link = new LinkButton();
link.CommandName = "LinkCommand";
link.Command += new CommandEventHandler(link_Command);
link.Text = "Yes";
link.ID = index.ToString();
label.Controls.Add(link);
}
else
{
PlaceHolder label = (PlaceHolder)e.Row.FindControl("HasPrevious");
Label noNote = new Label();
noNote.Text = "No";
label.Controls.Add(noNote);
}
Here is the gridview:
<asp:GridView runat="server" ID="LedgerGrid" AutoGenerateColumns="false"
onselectedindexchanged="LedgerGrid_SelectedIndexChanged"
onrowdatabound="LedgerGrid_RowDataBound" onrowcommand="LedgerGrid_RowCommand"
>
<Columns>
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:PlaceHolder ID="HasPrevious" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Invoice Date" DataField="invoicedate" DataFormatString="{0:d}" />
<asp:BoundField HeaderText="Invoice" DataField="invoice" />
<asp:BoundField HeaderText="Fee Debt" DataField="Fee_Debt" DataFormatString="{0:C}" />
<asp:BoundField HeaderText="Cost Debt" DataField="Cost_Debt" DataFormatString="{0:C}" />
<asp:BoundField HeaderText="VAT Debt" DataField="VAT_Debt" DataFormatString="{0:C}" />
<asp:BoundField HeaderText="Total Debt" DataField="Total_Debt" DataFormatString="{0:C}" />
<asp:BoundField HeaderText="Client Code" DataField="ClientCode" />
<asp:ButtonField HeaderText="Matter Number" DataTextField="matternumber" CommandName="ViewMatter" />
<asp:BoundField HeaderText="Decription" DataField="matterdescription" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="AddInvoiceCheck" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
To make sure that my link button command works I am rebuilding the gridview as I would in the Page_load. Here is the page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string clientCode = Server.HtmlEncode(Request.QueryString["clientcode"]);
items = DataAccess.DataAccess.GetLedgerDetails(clientCode);
ViewState["LedgerItems"] = items;
ViewState["clientcode"] = clientCode;
LedgerGrid.DataSource = items;
LedgerGrid.DataBind();
LedgerClientObject clientDetails = DataAccess.DataAccess.GetClientDetails(clientCode);
ClientCodeLabel.Text = string.Format("Group Code: {0}", clientDetails.GroupCode);
ClientNameLabel.Text = string.Format("Client Name: {0}", clientDetails.ClientName);
ClientCodeFilter.DataSource = clientDetails.ClientCodes;
ClientCodeFilter.DataBind();
}
}
To maintain the dynamically added controls on post back I am calling the following:
protected void Page_PreLoad(object sender, EventArgs e)
{
if (IsPostBack)
{
items = (List<LedgerItem>)ViewState["LedgerItems"];
LedgerGrid.DataSource = items;
LedgerGrid.DataBind();
}
}
Of course it now seems that by using this method I am overwriting the state of the check-box gridview column. Am I approaching this all wrong? I would like to be able to use the viewstate to maintain the set up of my dynamically added controls to the gridview. Is there a way I can access the state of the checkbox control form gridview before/after I reload the gridview in PreLoad event?
I am checking the state of my checkbox column with a button click as follows:
protected void Unnamed1_Click(object sender, EventArgs e)
{
NoteModel note = new NoteModel();
for (int i = 0; i < LedgerGrid.Rows.Count; i++)
{
int invoice = Convert.ToInt32(LedgerGrid.Rows[i].Cells[2].Text);
CheckBox check = (CheckBox)LedgerGrid.Rows[i].FindControl("AddInvoiceCheck");
if (check.Checked)
{
note.invoices.Add(invoice);
}
}
if (note.invoices == null)
{
string clientcode = (string)ViewState["clientcode"];
ViewState["InvoiceError"] = 1;
Response.Redirect(string.Format("Ledger.aspx?clientcode={0}", clientcode));
}
else
{
string clientcode = (string)ViewState["clientcode"];
Session["NoteObject"] = note;
Response.Redirect(string.Format("AddNote.aspx?cc={0}", clientcode));
}
}
Whenever I iterate over the checkbox controls in the gridview they are all unchecked e.g overwritten by my PreLoad code!!!
In the end I decided not to use dynamically created controls. Instead I added a buttonfield to the grid view. In my rowdatabound event I then set the visibility of the button to false if it does meet my criteria. This way view state is maintained as i do not need to create control on post back.
Seems with webforms that avoiding dynamic controls where possible is the best bet. I would still like to know which event to tap into to override viewstate re-instating controls?

Gridview with Enable and Disable image buttons

I have gridview in an asp.net application. I want to insert a column with image buttons where by click on it will enable or disable users or change the status field in db and also change the image button image accordingly user status.
Meaning: I want to display different images for disabled and enabled users.
How can I do this in C# and bind the data to the image button?
Anyone please help. Thanks in advance.
Make use of the ItemDataBound event. This is where you can check each row of your grid and apply changes to it. Then you can hide / unhide or change buttons:
VB.net below but you can easily convert to C#:
Dim ib As ImageButton = CType(e.Item.FindControl("ibFav"), ImageButton)
ib.Visible = False
Dim ib2 As ImageButton = CType(e.Item.FindControl("ibRemFav"), ImageButton)
ib2.Visible = True
Sample User Model:
public class UserModel {
public string Name { get; set; }
public bool IsEnabled { get; set; }
}
Here is the GridView Code:
<asp:GridView ID="GridView" runat="server" AutoGenerateColumns="false"
onrowcommand="GridView_RowCommand" onrowdatabound="GridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="EnabledImgBtn" runat="server"
CommandArgument='<%# Eval("Name") %>'
CommandName="ResetUserState" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
//Other columns....
</Columns>
</asp:GridView>
Set the 'CommandArgument' according to your needs. e.g the ID of the User.
Sample Code-behind for the gridview:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
LoadGridView();
}
}
private void LoadGridView()
{
this.GridView.DataSource = GetUsersFromDatabase();
this.GridView.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var user = e.Row.DataItem as UserModel;
var enabledImgBtn = e.Row.FindControl("EnabledImgBtn") as ImageButton;
if (enabledImgBtn != null)
enabledImgBtn.ImageUrl = user.IsEnabled ? "~/YourImagePath/enabled.png"
: "~/YourImagePath/disalbed.png";
}
}
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ResetUserState")
{
if (e.CommandArgument!= null)
{
var userName = e.CommandArgument.ToString();
//Change user enabled state and Update database
//Sample code:
var user = FindUserByName("userName");
user.IsEnabled = !user.IsEnabled;
//SaveInDatabase(user);
LoadGridView();
}
}
}
You may consider using 'CommandField' with Type equal to 'Image' instead of 'TemplateField', but there is an issue with this approach, read more.
Hope this helps.
<asp:GridView ID="GridView" runat="server" AutoGenerateColumns="false"
onrowcommand="GridView_RowCommand" onrowdatabound="GridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Change Status" ItemStyle-CssClass="GrdItemImg">
<ItemTemplate>
<asp:ImageButton ID="ibtnChangeActiveStatus" CommandArgument='<%#Eval("RecordID")%>'
CommandName='GRDSTATUS' runat="server" ImageUrl='<%# getStatusImage(Convert.ToInt32(DataBinder.Eval(Container.DataItem,"IsApproved"))) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Col2" HeaderText="Col2" />
//Other Respective columns....
...........
..........
</Columns>
</asp:GridView>
And In CS file add the following function.
public string getStatusImage(int intStatus)
{
string strStatus = string.Empty;
if (intStatus == 1)
{
strStatus = "~/images/active.png";
}
else
{
strStatus = "~/images/inactive.png";
}
return strStatus;
}
So on the base of "intStatus" respective active / InActive Image will be set.

ASP.NET GridView, enabling/disabling buttons after paging

I have successfully implemented my GridView now, but, as always, the whole ASP.NET life cycle thing is bothering me. I can't figure out why this doesn't work. I have bound the GridView's OnPageIndexChanged as such:
protected void GridView_PageIndexChanged(object sender, EventArgs e)
{
// Enable/disable the previous/next buttons.
LinkButton btnNextPage = (LinkButton)gvTable.BottomPagerRow.FindControl("btnNextPage");
LinkButton btnPreviousPage = (LinkButton)gvTable.BottomPagerRow.FindControl("btnPreviousPage");
btnNextPage.Enabled = false;
btnPreviousPage.Enabled = false;
}
This is my ASCX:
<asp:GridView ID="gvTable" runat="server" ShowHeader="true" PageSize="1"
AllowPaging="true" AllowSorting="true" DataSourceID="dsLinqActivities"
AutoGenerateColumns="false" OnRowDataBound="GridView_DataBound"
OnPageIndexChanged="GridView_PageIndexChanged">
<Columns>
<asp:BoundField DataField="Edited" HeaderText="Date" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:BoundField DataField="Activity" />
</Columns>
<PagerSettings Position="Bottom" Visible="true" />
<PagerStyle CssClass="pager" />
<PagerTemplate>
<asp:LinkButton ID="btnPreviousPage" class="navbtn prev left"
runat="server" CommandName="Page" CommandArgument="Prev">
<span>Newer activities</span></asp:LinkButton>
<asp:LinkButton ID="btnNextPage" class="navbtn next right"
runat="server" CommandName="Page" CommandArgument="Next">
<span>Older activities</span></asp:LinkButton>
</PagerTemplate>
</asp:GridView>
I debug my application and see that the code is being run and does the right thing but for some reason when the control is rendered, both of the buttons are always enabled. What am I doing wrong here?
If I were you, I would code it like this in the "GridView_PageIndexChanged" method
(gvTable.BottomPagerRow.FindControl("btnNextPage") as LinkButton).Enabled = true/false;
Edit:Can you also try adding a setter ?
set
{
gvTable.BottomPagerRow.FindControl("btnNextPage") as LinkButton =value;
}
Edit: OK my friend, I finally worked out a solution. May be not very elegant,but it works and I tested it. There are a few things to take care of:
1. We are having a "Prev" and a "Next" button and we got to handle "OnCommand" events for those since we are using our own Pager Template
2. We would have to bind data after we handle our OnCommand event.
I have a static List<String> which I populated during GET with random strings (Courtesy: http://www.kivela.be/index.php/2007/06/19/how-to-generate-a-random-string-in-c-20/) and bound them to my grid. You can substitute your own datasource here.Also, we have to change the grid's page index manually in our OnCommand Event.
Here is my aspx/ascx grid
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView_DataBound"
AllowPaging="true" PagerSettings-Mode="NextPrevious" PagerSettings-Position="Bottom" PageSize="10"
OnPageIndexChanged="GridView_PageIndexChanged">
<PagerSettings Position="Bottom" Visible="true" />
<PagerStyle CssClass="pager" />
<PagerTemplate>
<asp:LinkButton ID="btnPreviousPage" OnCommand="ChangePage"
runat="server" CommandName="Prev" Text="prev">
</asp:LinkButton>
<asp:LinkButton ID="btnNextPage" OnCommand="ChangePage"
runat="server" CommandName="Next" Text="next">
</asp:LinkButton>
</PagerTemplate>
</asp:GridView>
and here is the codebehind
public partial class TestPage : System.Web.UI.Page
{
private static Random _random = new Random();
static List<string> lst = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
for (int i = 1; i <= 30; i++)
{
lst.Add(RandomString(i));
}
GridView1.DataSource = lst;
GridView1.DataBind();
SetPageNumbers();
}
}
private void SetPageNumbers()
{
if (GridView1.PageIndex == 0)
{
(GridView1.BottomPagerRow.FindControl("btnPreviousPage")as LinkButton).Enabled = false;
}
if(GridView1.PageIndex ==GridView1.PageCount-1)
{
(GridView1.BottomPagerRow.FindControl("btnNextPage") as LinkButton).Enabled = false;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Prev":
GridView1.PageIndex = GridView1.PageIndex - 1;
break;
case "Next":
GridView1.PageIndex = GridView1.PageIndex + 1;
break;
}
GridView1.DataSource = lst;
GridView1.DataBind();
SetPageNumbers();
}
public static string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < size; i++)
{
//26 letters in the alfabet, ascii + 65 for the capital letters
builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65))));
}
return builder.ToString();
}
}
Hope this helps
Is there any chance your CSS is setting the enabled property?
I duplicated your code without the CSS and it works fine for me.
How about posting your css?

Categories

Resources