I use a session to save the hashtable. It has different key-value pairs in it and some of the keys refer to 'List' object.
I have different buttons in the repeater control to change the value of the List and then put it back to hashtable. Then use the same session to save that hashtable. But sometimes the change made get lost in the session. Don't know why. I tried on my test server. It can work fine. While on Prod server, I met this problem.
Any suggestions?
<asp:Repeater ID="rptCountry" runat="server" OnItemDataBound="rptCountry_ItemDataBound" OnItemCommand="rptCountry_ItemCommand">
<ItemTemplate>
<asp:Button ID="btnCountry" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Country").ToString() %>' CssClass="iButton Disabled" Enabled="false" UseSubmitBehavior="False" CommandName="Select" />
<asp:Label ID="hdnCountryCode" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "CountryCode")%>' Visible="false" />
</ItemTemplate>
</asp:Repeater>
protected void rptCountry_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("Select"))
{
Button btnCountry = (Button)e.Item.FindControl("btnCountry");
Label hdnCountryCode = (Label)e.Item.FindControl("hdnCountryCode");
if (Session["SearchFilter"] != null)
{
Hashtable htSearchFilter = (Hashtable)Session["SearchFilter"];
List<string> countries = (List<string>)htSearchFilter["Country"];
if (countries != null && countries.Count > 0)
{
bool countriesExists = false;
foreach (string country in countries)
{
if (country.Equals(hdnCountryCode.Text.Trim()))
{
countriesExists = true;
}
}
if (!countriesExists)
{
countries.Add(hdnCountryCode.Text.Trim());
btnCountry.CssClass = "iButton Active";
}
else
{
countries.Remove(hdnCountryCode.Text.Trim());
btnCountry.CssClass = "iButton";
}
}
else
{
countries.Add(hdnCountryCode.Text.Trim());
btnCountry.CssClass = "iButton Active";
}
htSearchFilter["Country"] = countries;
Session["SearchFilter"] = htSearchFilter;
ProvinceReloadControl(countries);
}
}
InitControl();
}
Related
I'm trying to modify this asp.net / C# code. The page lets an admin add a user and choose what roles this user will have from a list of checkboxes. There are 11 checkboxes with roles next to them to pick from. I'm wanting to organize these checkboxes. I'm wanting to divide the 11 checkboxes into 3 groups CMS, LMS, and Admin in order to group them into three sections on the page. I'm wanting only one checkbox to be selectable for the CMS group. The CMS group can be a dropdown box if that would make it easier. And, all of these roles must have a tooltip when the user hovers their mouse over them.
You'll see in the code that the checkboxes get created using the userRolesDataSource. This datasource uses a method called "GetUserRoles" which has two parameters the "username" and the "onlyIncludeSystemAdminRole" boolean. The selection method checks if the username is a system admin and excludes all other role choices if this is true.
This is the new GetUserRoles method:
public List<Pair<string, bool>> GetUserRoles(
string userName, bool onlyIncludeSystemAdminRole)
{
// Return a list of "role name"/"has role" pairs for the given user.
// If the "onlyIncludeSystemAdminRole" flag is true, only return the
// "System Admin" role, otherwise return all roles other than
// "System Admin".
List<Pair<string, bool>> userRolesList = null;
if (!onlyIncludeSystemAdminRole)
{
string[] allRoles = Roles.GetAllRoles();
HashSet<string> rolesForUser = null;
if (!String.IsNullOrWhiteSpace(userName))
{
rolesForUser = new HashSet<string>(
Roles.GetRolesForUser(userName));
}
userRolesList = (from roleName in allRoles
where roleName != RoleNames.SYSTEM_ADMIN
select new Pair<string, bool>()
{
First = roleName,
Second = rolesForUser != null
? rolesForUser.Contains(roleName)
: false
}).ToList();
}
else
{
userRolesList = new List<Pair<string, bool>>()
{
new Pair<string, bool>(
RoleNames.SYSTEM_ADMIN,
Roles.IsUserInRole(userName, RoleNames.SYSTEM_ADMIN))
};
}
return userRolesList;
}
Something like that will still have to be run on all the checkboxes.
In order to solve the problem I planned on using something like this method. It can be given a list of roles as a parameter. And, it'll exclude the list provided and return every other role.
public IEnumerable<string> GetRoles(params string[] roleNamesToExclude)
{
var query = Uow.Roles
.AsQueryable()
.Select(r => r.RoleName);
if (roleNamesToExclude != null && roleNamesToExclude.Any())
{
query = query
.Where(r => !roleNamesToExclude.Contains(r));
}
return query.ToList();
}
My idea for re-building it was to replace userRolesDataSource with 3 new datasources: CMSRolesDataSource, LMSRolesDataSource, AdminRolesDataSource. Then create a new method that takes username, systemadmin boolean, as well as a list of excludable roles like the method above.
I'm still pretty new to coding and I'm wondering if there's a simpler way of doing all of this. The code to the asp and c# are below. Thanks in advance.
asp
<asp:ObjectDataSource ID="userRolesDataSource" runat="server" OnSelecting="userRolesDataSource_Selecting" OldValuesParameterFormatString="{0}" SelectMethod="GetUserRoles" TypeName="VirtualExpertClinics.AutismProClassroom.Data.UserBLL">
<SelectParameters>
<asp:Parameter Name="userName" Type="String" />
<asp:Parameter Name="onlyIncludeSystemAdminRole" Type="Boolean" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="titlesDataSource" runat="server"
OldValuesParameterFormatString="{0}" SelectMethod="GetOrganizationTitles"
TypeName="VirtualExpertClinics.AutismProClassroom.Data.OrganizationBLL"
OnSelecting="titlesDataSource_Selecting">
<SelectParameters>
<asp:Parameter Name="organizationId" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<h5><%: Resources.Global.UserRoles %></h5>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" DataSourceID="userRolesDataSource" Enabled="false">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</ItemTemplate>
<EditItemTemplate>
<asp:Panel ID="userDetailsPanel" runat="server" DefaultButton="saveButton">
<table class="formTable extraCellPadding">
<tr>
<td class="alignTop">
<asp:Label ID="userRolesLabel" runat="server" Text="<%$ Resources:Global, UserRoles %>"></asp:Label>
</td>
<td>
<asp:CustomValidator ID="userRolesCustomValidator" runat="server" ValidationGroup="validationGroup"
OnServerValidate="userRolesCustomValidator_ServerValidate" Display="Dynamic">*</asp:CustomValidator>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" OnItemDataBound="userRolesDataList_ItemDataBound" DataSourceID="userRolesDataSource">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
<div style="margin-top: 1em;">
<asp:Button ID="saveButton" runat="server" CssClass="btn" ValidationGroup="validationGroup" CommandName="Update" Text="<%$ Resources:Global, Save %>" />
<asp:Button ID="cancelButton" runat="server" CssClass="btn" CommandName="Cancel" Text="<%$ Resources:Global, Cancel %>" />
</div>
</asp:Panel>
</EditItemTemplate>
<InsertItemTemplate>
<asp:Panel ID="userDetailsPanel" runat="server" DefaultButton="saveButton">
<table class="formTable extraCellPadding">
<tr>
<td class="alignTop">
<asp:Label ID="userRolesLabel" runat="server" CssClass="label" Text="<%$ Resources:Global, UserRoles %>"></asp:Label>
</td>
<td>
<asp:CustomValidator ID="userRolesCustomValidator" runat="server" ValidationGroup="validationGroup"
OnServerValidate="userRolesCustomValidator_ServerValidate" Display="Dynamic">*</asp:CustomValidator>
<asp:DataList ID="userRolesDataList" runat="server" CssClass="formTable" OnItemDataBound="userRolesDataList_ItemDataBound" DataSourceID="userRolesDataSource">
<ItemTemplate>
<asp:CheckBox ID="userRoleCheckBox" runat="server" Text='<%# Eval("First") %>' Checked='<%# Eval("Second") %>' />
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
<div style="margin-top: 1em;">
<asp:Button ID="saveButton" runat="server" CssClass="btn" ValidationGroup="validationGroup" CommandName="Insert" Text="<%$ Resources:Global, Save %>" />
<asp:Button ID="cancelButton" runat="server" CssClass="btn" CommandName="Cancel" Text="<%$ Resources:Global, Cancel %>" />
</div>
</asp:Panel>
</InsertItemTemplate>
</asp:FormView>
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (SessionWrapper.ActiveUserID == null)
{
userFormView.ChangeMode(FormViewMode.Insert);
}
}
}
protected void detailDataSource_Inserting(
object sender, ObjectDataSourceMethodEventArgs e)
{
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
List<string> roles = GetSelectedUserRoles(userRolesDataList);
if (SessionWrapper.WorkingOrganizationId != null)
{
e.InputParameters["organizationId"]
= SessionWrapper.WorkingOrganizationId;
}
else
{
e.InputParameters["organizationId"]
= SessionWrapper.ActiveOrganizationID;
}
e.InputParameters["acceptedAgreement"] = false;
e.InputParameters["changedPassword"] = false;
e.InputParameters["mustUpdateProfile"] = true;
e.InputParameters["timeZoneId"] = TimeZoneInfo.Utc.Id;
e.InputParameters["roles"] = roles;
e.InputParameters["registrationCodeId"] = null;
e.InputParameters["createPasswordTicket"] = true;
MiscUtil.TrimInputParameters(e.InputParameters);
}
protected void detailDataSource_Updating(
object sender, ObjectDataSourceMethodEventArgs e)
{
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
e.InputParameters["roles"] = GetSelectedUserRoles(userRolesDataList);
UserProfileDS.UserProfileRow user = UserBLL.GetUserByUserID(
(Guid)userFormView.SelectedValue);
e.InputParameters["acceptedAgreement"] = user.AcceptedAgreement;
e.InputParameters["changedPassword"] = user.ChangedPassword;
e.InputParameters["mustUpdateProfile"] = user.MustUpdateProfile;
e.InputParameters["timeZoneId"] = user.TimeZoneId;
MiscUtil.TrimInputParameters(e.InputParameters);
}
protected void userRolesDataList_ItemDataBound(
object sender, DataListItemEventArgs e)
{
Pair<string, bool> rolePair = (Pair<string, bool>)e.Item.DataItem;
if (rolePair.First == RoleNames.CMS_OWNER
|| rolePair.First == RoleNames.CMS_DATA_ENTRY
|| rolePair.First == RoleNames.CMS_BROWSER)
{
// Disable the CMS roles if CMS access is not enabled for the
// current organization.
OrganizationDS.OrganizationRow organizationRow
= OrganizationBLL.GetOrganizationById(
SessionWrapper.ActiveOrganizationID);
if (!organizationRow.EnableCMS)
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
userRoleCheckBox.ToolTip = Resources.Global.CMSNotEnabled;
}
}
else if (rolePair.First == RoleNames.WORKSHOPS_USER)
{
// Disable the "Workshops User" role if the corresponding
// check box is not selected and the current organization has
// reached their maximum number of learners.
if (!rolePair.Second
&& OrganizationBLL.HasReachedMaxLearners(
SessionWrapper.ActiveOrganizationID))
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
userRoleCheckBox.ToolTip
= Resources.Global.OrganizationMaxLearnersReached;
}
}
else if (rolePair.First == RoleNames.LOCAL_SYSTEM_ADMIN)
{
// Disable the "Local System Admin" role if the current user
// is not a system admin.
if (!Roles.IsUserInRole(RoleNames.SYSTEM_ADMIN))
{
CheckBox userRoleCheckBox = (CheckBox)e.Item.FindControl(
"userRoleCheckBox");
userRoleCheckBox.Enabled = false;
}
}
}
protected void userRolesDataSource_Selecting(
object sender, ObjectDataSourceSelectingEventArgs e)
{
string userName;
bool onlyIncludeSystemAdminRole;
if (userFormView.CurrentMode == FormViewMode.Insert)
{
userName = "";
onlyIncludeSystemAdminRole
= (SessionWrapper.ActiveOrganizationID == 0);
}
else
{
UserProfileDS.UserProfileRow userRow
= (UserProfileDS.UserProfileRow)userFormView.DataItem;
userName = userRow.UserName;
onlyIncludeSystemAdminRole = Roles.IsUserInRole(
userRow.UserName, RoleNames.SYSTEM_ADMIN);
}
e.InputParameters["userName"] = userName;
e.InputParameters["onlyIncludeSystemAdminRole"]
= onlyIncludeSystemAdminRole;
}
private List<string> GetSelectedUserRoles(DataList userRolesDataList)
{
List<string> roles = new List<string>();
foreach (DataListItem item in userRolesDataList.Items)
{
CheckBox userRoleCheckBox = (CheckBox)item.FindControl(
"userRoleCheckBox");
if (userRoleCheckBox.Checked)
{
roles.Add(userRoleCheckBox.Text);
}
}
return roles;
}
protected void userRolesCustomValidator_ServerValidate(
object source, ServerValidateEventArgs args)
{
CustomValidator userRolesCustomValidator = (CustomValidator)source;
DataList userRolesDataList = (DataList)userFormView.Row.FindControl(
"userRolesDataList");
List<string> roles = GetSelectedUserRoles(userRolesDataList);
AdministrationUtil.ValidateUserRoleSelection(
roles, userRolesCustomValidator, args);
}
}
I am trying to find the formview inside my listview on the page load. However, my result is always null. I called the DataBind method first but still nothing.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
String list = itemdropdownlist.SelectedValue;
switch (list)
{
case "Section Item":
SectionListView.DataBind();
//SectionListView.Enabled = false;
var temp = (FormView)SectionListView.FindControl("SectionFormView");
temp.Enabled = true;
renderView(SectionListView, "hidden"); // hide listview on page load
break;
}
}
ASP.net code
<InsertItemTemplate>
<tr style="">
<td>
<div style="font-size: .8em;">
<asp:FormView ID="SectionFormView" runat="server" DataKeyNames="SectionItemID" DataSourceID="SectionDataSource">
<ItemTemplate>
<asp:Button ID="InsertButton" runat="server" Text="Insert" OnClick="SectionItemButton_Click" Font-Size="1.2em" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" Font-Size="1.2em" />
<asp:Label ID="SectionItemLabel" runat="server" Text="SectionItem" Font-Bold="true" Font-Size="1.2em" />
<asp:TextBox ID="SectionItemTextBox" runat="server" />
<asp:Label ID="SectionItemSubLabel" runat="server" Text="SectionItem Label" Font-Bold="true" Font-Size="1.2em" />
<asp:TextBox ID="SectionItemLabelTextBox" runat="server" />
</ItemTemplate>
</asp:FormView>
</div>
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
You got that error, because the listview was not binded yet, so i think the best way would be to do all this on the ItemDataBound event. You would find the FormView like:
if (e.Item.ItemType == ListViewItemType.DataItem)
{
FormView SFormView= (FormView)e.Item.FindControl("SectionFormView");
if (SFormView!= null)
{
//code here
}
}
You could use this code to find about anything. I used it before to find Literals that I created in code behind. Use this code to find your FormView
private readonly List<FormView> _foundControls = new List<FormView>();
public IEnumerable<FormView> FoundControls
{
get { return _foundControls; }
}
public void FindChildControlsRecursive(Control control)
{
foreach (Control childControl in control.Controls)
{
if (childControl.GetType() == typeof(FormView))
{
_foundControls.Add((FormView)childControl);
}
else
{
FindChildControlsRecursive(childControl);
}
}
}
FindChildControlsRecursive(<Insert relevent Code Here: Whatever element you want to search inside of like your listView, find that using FindControl>);
FormView[] strControl = new FormView[200];
strControl = FoundControls.ToArray();
foreach (FormView i in strControl)
{
if (i.ID.Equals("< insert controlId of your FormView>"))
{
// do something when you find it
}
}
From a listview control, when checkboxes are checked and a button is clicked from outside the listview, I need to be able to delete the items that have been checked. Here's the listview:
EDIT
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
var notes = (from n in db.Notes
select n).OrderBy(n => n.FiscalYear).ThenBy(n => n.Period);
notesListView.DataSource = notes;
notesListView.DataBind();
}
<asp:ListView ID="notesListView" ItemPlaceholderID="itemPlaceholder" runat="server">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkNote" runat="server" />
<div><%# Eval("Period") %></div>
<div><%# Eval("FiscalYear") %></div>
<div><%# Eval("Account") %></div>
<div class="wrap"><%# Eval("Description") %></div>
</ItemTemplate>
<EmptyDataTemplate>
<div>No notes have been submitted.</div>
</EmptyDataTemplate>
</asp:ListView>
<br />
<asp:Button ID="deleteNotes" CssClass="deleteButton" Text="Delete Notes" runat="server" OnClick="deleteNotes_Click" />
Here's the code behind:
protected void deleteNotes_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in notesListView.Items)
{
// I know this is wrong, just not sure what to do
if (notesListView.SelectedIndex >= 0)
{
CheckBox ck = (CheckBox)item.FindControl("checkNote");
if (ck.Checked)
{
var index = item.DataItemIndex; // the item row selected by the checkbox
// db is the datacontext
db.Notes.DeleteOnSubmit(index);
db.SubmitChanges();
}
}
else
{
errorMessage.Text = "* Error: Nothing was deleted.";
}
}
}
You need to find the object before deleting it. To do so, I would add a hiddenfield to store NoteID like this:
<asp:HiddenField ID="hdnId" Value='<%#Eval("Id")%>' runat="server" />
<asp:CheckBox ID="checkNote" runat="server" />
... ... ...
And in my code I am finding the note by ID and deleting that note (You may use any other unique field instead of ID). My code may look like this:
... ... ...
int id = 0;
var hdnId = item.FindControl("hdnId") as HiddenField;
CheckBox ck = (CheckBox)item.FindControl("checkNote");
//I would check null for ck
if (ck != null && ck.Checked && hdnId != null && int.TryParse(hdnId.Value, out id)
{
// db is the datacontext
Note note = db.Notes.Single( c => c.Id== id );
db.Notes.DeleteOnSubmit(note );
db.SubmitChanges();
}
Before anyone answers this, I found the bug in my code, and posted my answer below. I'm leaving this question up (unless someone really cares) as a cautionary tale to always bind your bleeping GridView.
Preface/Background
I'm (ab)using the ASP.NET WebForms controls in an odd way. I know.
I'm working on an application where students are expected to list some school activities they've participated in. Students can add several rows, and -- just for general workflow reasons -- I decided to separate the GridView that displays their "saved" entries from the "details" area where they add/update their activities.
The Edit/Update pieces work beautifully. I can add new items, use baked-in validation that I tied into my classes (which is what all the extra span tags that have class="error" attributes display). I really wanted to make this idiot-proof, so the button they click to add a new activity will also validate and add their information to the GridView (provided the item passes validation), clear the Details controls, and behave as normal.
Problem Description
I started some basic testing on this, and found that if I edit an activity, break one (or more) of the validation rules in that class, and click the "Add New Activity" button, my GridView reverts that row from the EditItemTemplate back to the normal ItemTemplate.
As far as I can tell, my EditIndex never strays from the row I'm still editing. In fact, if I trigger another postback, the GridView shows the correct EditIndex!
I've tried re-setting the EditIndex and switched my e.Cancel = true to a return statement. Nothing's worked. Considering that the EditIndex's value stays constant through multiple postbacks, I have to think there's something weird going on here.
I've posted the markup and C# code below. Both are pretty absurdly long -- I refactor the hell out of my functions -- so I apologize in advance, and thank anyone brave enough (or bored enough) to offer advice.
Also, I can provide screenshots if anyone would rather see this happening instead of (or in addition to) reading through my markup/code.
GridView
<asp:GridView ID="schoolActivities" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="edit" CommandName="Edit" runat="server" Text="Edit" />
</ItemTemplate>
<EditItemTemplate></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<%# DataBinder.GetPropertyValue(Container.DataItem, "Details") %>
</ItemTemplate>
<EditItemTemplate>Editing...</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Months per Year
</HeaderTemplate>
<ItemTemplate><%# DataBinder.GetPropertyValue(Container.DataItem, "MonthsPerYear") %></ItemTemplate>
<EditItemTemplate></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Date</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.GetPropertyValue(Container.DataItem, "ActivityDate") %>
</ItemTemplate>
<EditItemTemplate></EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Total Hours Outside Class Time
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.GetPropertyValue(Container.DataItem, "TotalHours") %>
</ItemTemplate>
<EditItemTemplate></EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
"Details" section
<br />
<button type="button" id="newActivity" runat="server">Add New Activity</button>
<br />
<fieldset id="schoolActivityFields" runat="server" visible="false">
<legend>Activity</legend>
<span>Details:</span>
<span>
<textarea id="schoolActivityDetails" class="schoolActivityDetails" runat="server"></textarea>
<br />
<span id="schoolActivityDetailsError" class="error" runat="server"></span>
</span>
<br />
<span>Months per Year:</span>
<span>
<select id="schoolActivityMonthsPerYear" runat="server">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</span>
<span id="schoolActivityMonthsPerYearError" class="error" runat="server"></span>
<br />
<span>Date:</span>
<span>
<select id="schoolActivityDate" runat="server">
<option>2005</option>
<option>2006</option>
<option>2007</option>
<option>2008</option>
<option>2009</option>
<option>2010</option>
<option>2011</option>
<option>2012</option>
</select>
</span>
<span id="schoolActivityDateError" class="error" runat="server"></span>
<br />
<span>Total Hours:</span>
<span>
<input type="text" id="schoolActivityTotalHours" runat="server" />
</span>
<span id="schoolActivityTotalHoursError" class="error" runat="server"></span>
<br />
<button type="button" id="addActivity" runat="server">Add Activity</button>
<button type="button" id="updateActivity" runat="server" visible="false">Update Activity</button>
<button type="button" id="cancelEditActivity" runat="server" visible="false">Cancel Editing Activity</button>
<button type="button" id="deleteActivity" runat="server" visible="false">Delete Activity</button>
</fieldset>
The C# is monstrous in length, but for any brave souls:
void addActivity_ServerClick(object sender, EventArgs e)
{
AddSchoolActivity();
}
private bool AddSchoolActivity()
{
ResetSchoolActivityErrors();
SchoolActivity activityToAdd = GetSchoolActivity();
try
{
SessionApplication.SchoolActivities.Add(activityToAdd);
BindSchoolActivities();
ResetSchoolActivityFields();
HideSchoolActivityFields();
}
catch (BrokenRuleException)
{
MapSchoolActivityErrors(activityToAdd);
return false;
}
return true;
}
void updateActivity_ServerClick(object sender, EventArgs e)
{
UpdateSchoolActivity();
}
private bool UpdateSchoolActivity()
{
ResetSchoolActivityErrors();
SchoolActivity activityToUpdate = GetSchoolActivity();
try
{
SessionApplication.SchoolActivities[schoolActivities.EditIndex] = activityToUpdate;
ResetSchoolActivitiesEditIndex();
BindSchoolActivities();
ResetSchoolActivityFields();
HideSchoolActivityFields();
}
catch (BrokenRuleException)
{
MapSchoolActivityErrors(activityToUpdate);
SetSchoolActivitiesEditIndex(schoolActivities.EditIndex);
return false;
}
return true;
}
private SchoolActivity GetSchoolActivity()
{
SchoolActivity currentActivity = new SchoolActivity();
currentActivity.Details = schoolActivityDetails.Value;
TryGetSchoolActivityMonthsPerYear(currentActivity);
TryGetSchoolActivityDate(currentActivity);
TryGetSchoolActivityTotalHours(currentActivity);
return currentActivity;
}
private void TryGetSchoolActivityMonthsPerYear(SchoolActivity currentActivity)
{
byte monthsPerYear;
if (byte.TryParse(schoolActivityMonthsPerYear.Value, out monthsPerYear))
{
currentActivity.MonthsPerYear = monthsPerYear;
}
}
private void TryGetSchoolActivityDate(SchoolActivity currentActivity)
{
short activityDate = -1;
if (short.TryParse(schoolActivityDate.Value, out activityDate))
{
currentActivity.ActivityDate = activityDate;
}
}
private void TryGetSchoolActivityTotalHours(SchoolActivity currentActivity)
{
short totalHours = -1;
if (schoolActivityTotalHours.Value.IsNullOrWhiteSpace() == false
&& short.TryParse(schoolActivityTotalHours.Value, out totalHours))
{
currentActivity.TotalHours = totalHours;
}
}
private void ResetSchoolActivityFields()
{
schoolActivityDetails.Value = string.Empty;
schoolActivityMonthsPerYear.SelectedIndex = 0;
schoolActivityDate.SelectedIndex = 0;
schoolActivityTotalHours.Value = string.Empty;
}
private void HideSchoolActivityFields()
{
schoolActivityFields.Visible = false;
}
private void MapSchoolActivityErrors(int activityIndex)
{
SchoolActivity updatedActivity = SessionApplication.SchoolActivities[activityIndex];
MapSchoolActivityErrors(updatedActivity);
}
private void MapSchoolActivityErrors(SchoolActivity updatedActivity)
{
foreach (RuleViolation currentViolation in updatedActivity.GetRuleViolations())
{
schoolActivityErrorMapping[currentViolation].InnerText = currentViolation.ErrorMessage;
}
}
private void ResetSchoolActivityErrors()
{
foreach (RuleViolation currentViolation in schoolActivityErrorMapping.Keys)
{
schoolActivityErrorMapping[currentViolation].InnerText = string.Empty;
}
}
void schoolActivities_RowEditing(object sender, GridViewEditEventArgs e)
{
if (schoolActivities.EditIndex != e.NewEditIndex
&& schoolActivities.EditIndex != -1)
{
ResetSchoolActivityErrors();
SchoolActivity activityToUpdate = GetSchoolActivity();
try
{
SessionApplication.SchoolActivities[schoolActivities.EditIndex] = activityToUpdate;
}
catch (BrokenRuleException)
{
MapSchoolActivityErrors(activityToUpdate);
e.Cancel = true;
}
}
if (e.NewEditIndex != -1)
{
SchoolActivity activityToEdit = SessionApplication.SchoolActivities[e.NewEditIndex];
SetSchoolActivityFields(activityToEdit);
ShowSchoolActivityFields();
ShowModifyActivityButtons();
}
SetSchoolActivitiesEditIndex(e.NewEditIndex);
BindSchoolActivities();
}
private void ShowModifyActivityButtons()
{
addActivity.Visible = false;
updateActivity.Visible = true;
cancelEditActivity.Visible = true;
deleteActivity.Visible = true;
}
private void SetSchoolActivityFields(SchoolActivity activityToEdit)
{
schoolActivityDetails.Value = activityToEdit.Details;
schoolActivityMonthsPerYear.Value = activityToEdit.MonthsPerYear.ToString();
schoolActivityDate.Value = activityToEdit.ActivityDate.ToString();
schoolActivityTotalHours.Value = activityToEdit.TotalHours.ToString();
}
private bool ShowSchoolActivityFields()
{
return schoolActivityFields.Visible = true;
}
private void BindSchoolActivities()
{
schoolActivities.DataSource = SessionApplication.SchoolActivities;
schoolActivities.DataBind();
}
void newActivity_ServerClick(object sender, EventArgs e)
{
if (SessionApplication.SchoolActivities.Count < SchoolActivityList.Rules.MaxCount)
{
if (schoolActivities.EditIndex != -1)
{
if (UpdateSchoolActivity() == false)
{
return;
}
}
else if (schoolActivityFields.Visible)
{
if (AddSchoolActivity() == false)
{
return;
}
}
ShowSchoolActivityFields();
ShowAddActivityButtons();
}
}
private void ShowAddActivityButtons()
{
addActivity.Visible = true;
updateActivity.Visible = false;
cancelEditActivity.Visible = false;
deleteActivity.Visible = false;
}
void ResetSchoolActivitiesEditIndex()
{
SetSchoolActivitiesEditIndex(-1);
}
void SetSchoolActivitiesEditIndex(int rowIndex)
{
schoolActivities.EditIndex = rowIndex;
}
Sigh. I missed a call to my binding function.
UpdateSchoolActivity() should look like this:
private bool UpdateSchoolActivity()
{
ResetSchoolActivityErrors();
SchoolActivity activityToUpdate = GetSchoolActivity();
try
{
SessionApplication.SchoolActivities[schoolActivities.EditIndex] = activityToUpdate;
ResetSchoolActivitiesEditIndex();
BindSchoolActivities();
ResetSchoolActivityFields();
HideSchoolActivityFields();
}
catch (BrokenRuleException)
{
MapSchoolActivityErrors(activityToUpdate);
SetSchoolActivitiesEditIndex(schoolActivities.EditIndex);
BindSchoolActivities(); // That little guy? Don't worry about that little guy.
return false;
}
return true;
}
I have this repeater on my page..Under the default column what I want is that there
should be an IF condition that checks my table's "IsDEfault" field value.
If IsDefault=True then the lable below "label1" ie "Yes" should be
displayed inside the repeater else "Make DEfault" link should be displayed..
Now how do I include this IF statement as inline code in my repeater to accomplish what I want ?
<asp:LinkButton ID="lnk1" Text="Make Default" CommandName="SetDefault" runat="server" Visible="True" CommandArgument='<%#Eval("UserID") %>' CausesValidation="false"></asp:LinkButton>
<asp:Label ID="label1" Text="Yes" runat="server" Visible="False"></asp:Label>
I have an idea :-
<%# If DataBinder.Eval(Container.DataItem,"IsDefault") = "True"
Then%>
<%End If%>
How should I form the "Then" statement now?
Please help me with the proper syntax..thnx
Do I need to like make a method that checks if "IsDefault" is true or not and then call it inside of inline code in my repeater ? How do I go about it ?
[EDIT]
I tried as follows:-
<% If (Eval("Container.DataItem,"IsDefault"")="True"?
("<asp:LinkButton ID="lnk1" Text="Set as Default" CommandName="SetDefault1" runat="server" CommandArgument='<%#Eval("User1ID") %>'
CausesValidation="false" Visible=true></asp:LinkButton>") : ("<asp:Label ID="label1" Text="Yes" runat="server" Visible=true></asp:Label>")
)%>
didnt work :( Help!!
If you want some control to be visible only on some condition, set the Visible property according to that condition:
<asp:Label ID="label1" Text="Yes" runat="server"
Visible="<%# DataBinder.Eval(Container.DataItem,"IsDefault") %>" />
EDIT
If you want the control INvisible for the "IsDefault" situation, reverse the test with something like Visible="<%# DataBinder.Eval(Container.DataItem,"IsDefault")==False %>".
I'm not quite sure about the exact syntax, but you should get the idea.
Here's your repeater markup. Notice both controls are hidden at the start:
<asp:Repeater runat="server" ID="rpt1" OnItemDataBound="rpt1_ItemDataBound" onitemcommand="rpt1_ItemCommand">
<ItemTemplate>
<p>
ID: <%# Eval("Id") %>
IsDefault: <%# Eval("IsDefault") %>
Name: <%# Eval("Name") %>
<asp:Label BackColor="Blue" ForeColor="White" runat="server" ID="lDefault" Text="DEFAULT" Visible="false" />
<asp:Button runat="server" ID="btnMakeDefault" Text="Make Default" Visible="false" CommandArgument='<%# Eval("Id") %>' />
</p>
</ItemTemplate>
</asp:Repeater>
And some code to go with it. Note I've simulated the retrieval of your collection of blluser objects, so there is some additional code there relating to this which you won't require as, presumably the bllusers collection that you bind to is coming from a db or something?
Anyway I think this is what you're looking for, but let me know if its not ;-)
//Dummy object for illustrative purposes only.
[Serializable]
public class bllUsers
{
public int Id { get; set; }
public bool isDefault { get; set; }
public string Name { get; set; }
public bllUsers(int _id, bool _isDefault, string _name)
{
this.Id = _id;
this.isDefault = _isDefault;
this.Name = _name;
}
}
protected List<bllUsers> lstUsers{
get
{
if (ViewState["lstUsers"] == null){
ViewState["lstUsers"] = buildUserList();
}
return (List<bllUsers>)ViewState["lstUsers"];
}
set{
ViewState["lstUsers"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
buildGui();
}
}
private List<bllUsers> buildUserList(){
lstUsers = new List<bllUsers>();
lstUsers.Add(new bllUsers(1, false, "Joe Bloggs"));
lstUsers.Add(new bllUsers(2, true, "Charlie Brown"));
lstUsers.Add(new bllUsers(3, true, "Barack Obama"));
return lstUsers;
}
private void buildGui()
{
rpt1.DataSource = lstUsers;
rpt1.DataBind();
}
protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
bllUsers obj = (bllUsers)e.Item.DataItem;//this is the actual bllUser the row is being bound to.
//Set the labels
((Label)e.Item.FindControl("ldefault")).Visible = obj.isDefault;
((Button)e.Item.FindControl("btnMakeDefault")).Visible = ! obj.isDefault;
//Or use a more readable if/else if you want:
if (obj.isDefault)
{
//show/hide
}
else
{
//set visible/invisible
}
}
}
Hope this helps :-)
Sorry to say you to be honest i was unable to understand what actually you wanted to do
If your looking to use the condition in the Item Templet then i think
the following systax will help you
<asp:LinkButton ID="Label1" runat="server"
Text='<%# ((Eval("Cond"))="True" ? Eval("Result for True") : Eval("Result for False") )%>'></asp:LinkButton>