How can I change the dropdownlist's options? - drop-down-menu

I'm a newbie in asp.net so I'm hoping you could give me some help on my dropdownlist bound to a table.
Here's the scenario:
I have a table Account with fields UserId, UserName and Type. The Type field contains 3 items: 'S', 'A', and 'U'. Each user has his own Type. I have a dropdownlist named 'ddlType' which is already
bound on the Account table. However, I want the options of the dropdownlist to be displayed as 'Stakeholder', 'Approver', and 'User' instead of displaying letters/initials only. Since I do not prefer making any changes in the database, how can I change those options through code behind?
Here's my code:
public void BindControls(int selectedUserId)
{
DataTable dtAccount = null;
try
{
dtAccount = LogBAL.GetAccountDetails(selectedUserId);
if (dtAccount.Rows.Count > 0)
{
lblUserId.Text = dtAccount.Rows[0]["UserId"].ToString();
txtUserName.Text = dtAccount.Rows[0]["UserName"].ToString();
ddlType.SelectedValue = dtAccount.Rows[0]["Type"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
dtAccount.Dispose();
}
}
Any help from you guys will be appreciated. Thanks in advanced! :D

You can bind Dropdownlist in codebehind.
Get your data "Type" into array. Make array two dimentional and assign values to it.
After having data your array will looks like this,
string[,] Types = { { "Stakeholder", "S" }, { "Approver", "A" }, { "User", "U" } };
Now assign values to Dropdown,
int rows = Types.GetUpperBound(0);
int columns = Types.GetUpperBound(1);
ddlType.Items.Clear();
for (int currentRow = 0; currentRow <= rows; currentRow++)
{
ListItem li = new ListItem();
for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
{
if (currentColumn == 0)
{
li.Text = Types[currentRow, currentColumn];
}
else
{
li.Value = Types[currentRow, currentColumn];
}
}
ddlType.Items.Add(li);
}
I haven't tested it but hopefully it will work.

Related

How to check if the user doesn't select any item in the list?

I have a list view that list the activities. I have a way to get the selected values. What I don't know is how can I check if the user doesn't select any items from the list. How can I do this?
This is how I populate my list this will return at least 5-20 activities:
public void Get_Activities()
{
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getActivity = conn.QueryAsync<ActivityTable>("SELECT * FROM tblActivity WHERE Deleted != '1' ORDER BY ActivityDescription");
var resultCount = getActivity.Result.Count;
if (resultCount > 0)
{
var result = getActivity.Result;
lstActivity.ItemsSource = result;
lstActivity.IsVisible = true;
}
else
{
lstActivity.IsVisible = false;
}
}
catch (Exception ex)
{
//Crashes.TrackError(ex);
}
}
And this is how I get the values of the selected items on my list:
foreach(var x in result)
{
if (x.Selected)
{
// do something with the selected items
}
}
My question is like this
if(list.selecteditemcount == 0){
DisplayAlert("Error","Please select atleast 1 item","Ok");
}
In xamarin projects you can use Linq (using System.Linq). With Linq it's really easy to filter your list like that:
if(!list.Any(x => x.Selected == true))
{
// DisplayAlert...
}
This basically checks if any of your items has the value Selected='true'
Or without Linq you can do something like this:
if(list.FindAll(x => x.Selected).Count() == 0)
{
//DisplayAlert...
}
Use this
if (result.Any(x => x.Selected))
{
}
else
{
await DisplayAlert("Application Error", "Please choose at least one(1) activity", "Ok");
}

Gridview not showing data for a particular field in linq

I want to data in gridview for a particular mail_id. but wheneven i add this where condition its not showing anything. please help
if (!IsPostBack)
{
var mail = lblmail.Text;
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
foreach (var items in result)
{
gvjob.DataSource = result;
gvjob.DataBind();
}
}
Is this better?
{
var mail = lblmail.Text;
// here, I assume jobposting is a DataTable
if (0 < je.jobposting.Rows.Count) {
var result = from test in je.jobposting orderby test.post_date where test.c_j_email==mail select test;
if (result.Any()) {
gvjob.DataSource = result;
gvjob.DataBind();
} else {
Response.WriteLine("No Match for c_j_email=" + mail + ".");
}
} else {
Response.WriteLine("<b>No Data in jobposting DataTable!</b>");
}
}

Dynamically Set Column Name In LINQ Query

Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);

LINQ in Business Layer paging / sorting gridview in User layer

I have a gridview in my user layer that uses a business layer method as its datasource, and I want the gridview to support paging and sorting. When I returned an Ienumerable from the method, it will bring back all of the data. If I use Take/Skip to bring back only a page's worth, the gridview doesn't realize that there are many pages of data.
When I change the Ienumerable to an IQueryable, the DataBind() fails because the data has already been disposed of. I think this problem has something to do with when the query actually executes and it may have to do with the filters I am applying to the query (see below).
User Layer Code:
grdSelectedQuestionaires.DataSource = assessment.FilteredAssessmentList(filter);
grdSelectedQuestionaires.DataBind(); <-- Fails - "Cannot access a disposed object"
Business Layer Code:
public IQueryable<Assessment> FilteredAssessmentList(AssessmentSearchFilter filter)
{
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
var rows = (
from a in dc.vPAQSummaries
select new Assessment()
{
PAQNumber = a.PAQNumber.Trim(),
CustomerID = (int)a.CustomerID,
Department = a.Department.Trim(),
CustomerName = a.CustomerName.Trim(),
DOTNumber = a.DOTNumber.Trim(),
OrgName = a.OrgName.Trim(),
DateEntered = a.DateEntered,
GroupNumber = a.GroupNumber.Trim(),
JobTitle = a.JobTitle.Trim(),
FileNames = a.FileNames.Trim(),
AnalystType = a.AnalystType.ToString(),
Incumbents = a.Incumbents,
});
// Filter by Customer ID
if (filter.CustomerID > 0)
{
rows = rows.Where(r => r.CustomerID == filter.CustomerID);
}
else
{
rows = rows.Where(r => r.CustomerID != null);
}
// Filter by DOT Number
if (!string.IsNullOrEmpty(filter.DOTNumberFrom))
{
if (string.IsNullOrEmpty(filter.DOTNumberTo))
{
rows = rows.Where(r => r.DOTNumber == filter.DOTNumberFrom);
}
else
{
rows = rows.Where(r => r.DOTNumber.CompareTo(filter.DOTNumberFrom) >= 0
&& r.DOTNumber.CompareTo(filter.DOTNumberTo) <= 0);
}
}
// Filter by OrgName
if (!string.IsNullOrEmpty(filter.OrgName))
{
rows = rows.Where(r => r.OrgName.StartsWith(filter.OrgName));
}
// Filter by Group
if (!string.IsNullOrEmpty(filter.GroupNumberFrom))
{
if (!string.IsNullOrEmpty(filter.GroupNumberTo))
{
rows = rows.Where(r => r.GroupNumber == filter.GroupNumberFrom);
}
else
{
rows = rows.Where(r => r.GroupNumber.CompareTo(filter.GroupNumberFrom) >= 0
&& r.GroupNumber.CompareTo(filter.GroupNumberTo) <= 0);
}
}
if (filter.Skip > 0)
{
rows = rows.Skip(filter.Skip);
}
if (filter.Take > 0)
{
rows = rows.Take(filter.Take);
}
else
{
rows = rows.Take(100);
}
return rows.Distinct();
}
}
}
The paging problem was caused by the Using statement. Changing this:
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
...
}
to this:
PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext();
Made paging work. Now I have to figure out how sorting works.

Expand all items in RadGrid Hierarchy

I am using a RadGrid (2009 Q2) with a hierarchy. Is there a way in the client api to expand all rows and vice-versa?
thanks!
Update:
I have written a javascript function based off the api documentation suggested by Dick Lampard below to expand/collapse all rows in a radgrid with three levels. It expands all the mastertableview rows and all the nested detailtableview rows in both sub levels of the first mastertableview row, but it breaks when it goes the to detailtableview rows for the second mastertableview row (whew!). The error I am getting is "_350 is undefined". This is coming from a Telerik.Web.UI.WebResource file.
function ExpandCollapseAll(expand) {
var grid = $find("<%= rgHistory.ClientID %>");
master = grid.get_masterTableView();
var masterRowCount = master.get_dataItems().length;
for (masterIndex = 0; masterIndex < masterRowCount; masterIndex++) {
if (expand) {
master.expandItem(masterIndex);
}
else {
master.collapseItem(masterIndex);
}
}
var detailTables = grid.get_detailTables();
var detailTableCount = detailTables.length;
for (detailTableIndex = 0; detailTableIndex < detailTableCount; detailTableIndex++) {
var detailTable = detailTables[detailTableIndex];
var rowCount = detailTable.get_dataItems().length;
for (rowIndex = 0; rowIndex < rowCount; rowIndex++) {
if (expand) {
//expandItem is failing! detailTableIndex and rowIndex are correct
detailTables[detailTableIndex].expandItem(rowIndex);
}
else {
detailTables[detailTableIndex].collapseItem(rowIndex);
}
}
}
}
ANY IDEAS?!?!
There is client API for hierarchy expansion as well as ExpandHierarchyToTop() server method. Check out this demo.
Dick
If you would like to see all the hierarchy levels, Set HierarchyDefaultExpanded to the MasterTableView and all the GridTableViews. See this link for more details.
Try This
protected void Page_PreRenderComplete() {
if (!Page.IsPostBack) {
foreach (GridItem item in MyGrid.MasterTableView.Controls[0].Controls) {
if (item is GridGroupHeaderItem)
if (item.GroupIndex.ToString() != "0")
item.Expanded = !item.Expanded;
}
}
}
after radGrid.DataBind()
use this Mehtod
private void ExpanadAllRadGridNodes()
{
foreach (GridDataItem item_L1 in radgridQuestionGroups.MasterTableView.Items)
{
foreach (GridTableView item_L2 in (item_L1 as GridDataItem).ChildItem.NestedTableViews)
{
foreach (GridDataItem item_L3 in item_L2.Items)
{
item_L3.Expanded = true;
}
}
}
}

Resources