LINQ - SELECT NEW - Include ListBox Selected Items - asp.net

Using ASP.NET 4.0
I am having trouble on the LINQ to get the .srvc_id to be the checked values and my query below is only populating the first check box for my object.
Code
If Not IsNothing(lbServices.SelectedItem) Then
'NEW record INSERT values from list box to table.
myServices = (From item In lbServices.Items
Where item.Selected
Select New tbl_parent_to_child With
{
.id = myServices.child_id,
----- .srvc_id is where I am stuck any help would be great. It is repeating the first selected check box.
.srvc_id = lbServices.SelectedValue,
.Active = True,
.CreateDate = DateTime.Now,
.CreateByID = SecurityMethods.GetLoginUserId(Session("AuthUser")),
.UpdateDate = DateTime.Now,
.UpdateByID = SecurityMethods.GetLoginUserId(Session("AuthUser"))
}).ToList()
For Each item In myServices
ctx.tbl_parent_to_child .Add(item)
Next
End If
Try
ctx.SaveChanges()
Catch ex As Exception
Me.Master.HandleStatusMessageEvent((New StatusMessageEventArgs("Email a screen shot of this error to the Help Desk", StatusMessageType.ErrorMsg)))
End Try

I believe you want to use the item variable, .srvc_id = CInt(item.Value)
This is similar to Listbox in asp.net not getting selected items

Related

Dynamic Dropdown issue

Hello I am trying to implement a drop down in asp.net. The drop down is being loaded from database and is being binded with drop down. The list has various values and text. But I want to add the first option of "Please Select" which is disabled for selection at the top of drop down list. Also on binding the drop down I want to point to the value which user had previously selected so that's why I am using selectedValue option. the problem is if I add the first item as "please select" from code behind at item 0 and selectedvalue to the value stored in db it still shows me item zero" please select".
DropDownList ddlMinEdit = (DropDownList)currentGrid.Rows
[currentGrid.EditIndex].FindControl("ddlMinEdit");
ddlMinEdit.Items.Insert(0, "Select Please");
ddlMinEdit.Items [0].Attributes.Add("disabled", "disabled");
ddlMinEdit.DataSource = CList;
ddlMinEdit.DataTextField = "empid";
ddlMinEdit.DataValueField = "empname";
ddlMinEdit.DataBind();
ddlMinEdit.SelectedValue = defemp;
So any suggestion how do I add first item and at same time bind a list and point to selected value. thanks
The order that you are doing things doesn't seems correct. You should insert the "Select Please" after the data binding and setting the selected value:
DropDownList ddlMRCClinEdit = (DropDownList)currentGrid.Rows [currentGrid.EditIndex].FindControl("ddlMRCClinEdit");
ddlMRCClinEdit.DataSource = clinList;
ddlMRCClinEdit.DataTextField = "empid";
ddlMRCClinEdit.DataValueField = "empname";
ddlMRCClinEdit.DataBind();
ddlMRCClinEdit.SelectedValue = defemp;
ddlMRCClinEdit.Items.Insert(0, "Select Please");
ddlMRCClinEdit.Items [0].Attributes.Add("disabled", "disabled");

How to return unique index value of multiple items selected in listbox

I have a listbox in VB.NET that allows users to select multiple categories. I need to put these categories into a database and need the index value from the listbox of the categories as the database works off IDs. SelectedItems (with an s) does not work in the net application.
I have tried the following code:
For Each category As ListItem In CategoryListBox.Items
If category.Selected Then
Dim courseCategory As New CourseCategory
courseCategory.CourseID = course.ID
courseCategory.CategoryID = CategoryListBox.SelectedIndex
Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
courseCategoryEntities.CourseCategories.Add(courseCategory)
courseCategoryEntities.SaveChanges()
End Using
End If
Next
When iterating through the loop the code that is:
courseCategory.CategoryID = CategoryListBox.SelectedIndex
works correctly the first time around.
On the second iteration of the loop, it goes to the next selected item however returns the index for the first selected value. How do I return the values of the other indexes selected?
It depends on what ID you need to pass to your database. If it is truly the index of the ListItem in the ListBox, then you would use:
courseCategory.CategoryID = CategoryListBox.Items.IndexOf(category);
That may not be the best approach however. Maybe the order of the ListItems changes, messing up your indexes. You probably want to store the actual CategoryID on each ListItem. The Value property works well for that. You set the column you want as the DataValueField like so:
<asp:ListBox ID="CategoryListBox" runat="server"
DataValueField="CategoryID "></asp:ListBox>
So as you are looping through each ListItem in the ListBox and checking if it is selected, just use it's Value property.
For Each category As ListItem In CategoryListBox.Items
If category.Selected Then
Dim courseCategory As New CourseCategory
courseCategory.CourseID = course.ID
courseCategory.CategoryID = category.Value;
Using courseCategoryEntities As New Eng_NWDTrainingWebsiteEntities
courseCategoryEntities.CourseCategories.Add(courseCategory)
courseCategoryEntities.SaveChanges()
End Using
End If
Next
Fixed the code by deselecting the item in the listbox after it was successfully saved.
End Using
category.Selected = False
End If
This solved my problem.

Item add in bottom of drop down list with value field

how i can add item in bottom whenever i am bind the gridview dynamic.
and i want a value field. because i have a search criteria with drop down list.
With Drop Down List Value I am sending the value with drop down list .
SqlParameter[] param3 = new SqlParameter[] { new SqlParameter("#status","org")
};
ddlDistrictCode.DataSource = comnFunctionObj.getDropDownList(clsConstant.GET_ALL_DROPDOWN, param3);
ddlDistrictCode.DataTextField = "DisplayFieldText";
ddlDistrictCode.DataValueField = "ValueFieldText";
ddlDistrictCode.DataBind();
Search Criteria
By this I am sending the value
new SqlParameter("#DISTRICTCODE",Convert.ToInt32((ddlDistrictCode.SelectedValue))),
After you databind, just add the value manually:
ddlDistrictCode.Items.Insert(lst.Items.Count - 1, new ListItem("VALUE", "TEXT"));

Insert initial blank row into select list MVC LINQ SQL

I have the following code that is in my formViewModel to be passed to my View.
var ownerValues = aspnet_Users
.OrderBy(u => u.Surname)
.Select(u => new KeyValuePair<int, string>(u.UserId, u.Surname + " " + u.Forename.ToString() + " [" + u.UserName.ToString() + "]"));
this.OwnersList = new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);
When I run the view in explorer my drop list defaults to the first item and I want it to default to a blank row.
So my plan is to insert a initial row with userId = null and then an empty string instead of 'please select' or something similar.
Can anyone please advise me on how to do this on one line of code I think, not sure where to start.
thanks
When Rendering your SelectList you can do something like
<%:Html.DropDownListFor(x => x.ApprovalType, Model.ApprovalTypes,"")%>
if you want strongly typed list or you can try
<%:Html.DropDownList("ApprovalType", Model.ApprovalTypes, "") %>
in both examples Model.ApprovalTypes contains a SelectList or List of SelectListItems. Empty string parameter at the end is optional label and its value is also an empty string
Edit Inserting label (empty string or something else) with some value will also create problems when you try to validate it using data annotations. Selecting empty label will not trigger the error message because associate value will be -1 (not empty) as suggested in other answer.
userid cannot be null (since it's int) but if -1 works, you can try
this.OwnersList = new SelectList(new[]{new KeyValuePair<int, string>(-1, "please select")}.Union(ownerValues), "Key", "Value", incidentAction.OwnerId);
Create your own List<SelectListItem> and then do an Insert
List<SelectListItem> MyOwnerList = new List<SelectListItem>();
MyOwnerList.AddRange(new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId);
MyOwnerList.Insert(0, new SelectListItem{Text = "", Value = ""});
this.OwnersList =MyOwnerList;

How to set dropdown's firsl Item -Select- and remaining Items from a column of table?

I m using a dropdown to display "Location" field of a table. I want to set first item of dropdowm as "-Select Location-". I can't set tables first record as "Select" because table is stroed in xml format. And table file is generated dynamicaly.
I am currentaly using as
ddlLocationName.Dispose();
ddlLocationName.AppendDataBoundItems = true;
ddlLocationName.Items.Add("Select Location");
ddlLocationName.DataSource = _section.GetLocations();
ddlLocationName.DataBind();
ddlLocationName.AppendDataBoundItems = false;
but data is binded repeatedly.
What will be the solution for this problem?
Thaks in advance.
After you have databound, then call ddlLocationName.Items.Insert(0, "Select Location");
Example:
ddlLocationName.Items.Clear();
ddlLocationName.DataSource = _section.GetLocations();
ddlLocationName.DataBind();
ddlLocationName.Items.Insert(0, "Select Location"); // Adds the item in the first position
Access the items in the form of ListItems:
ListItem li = new ListItem("Select Location","-1");
ddlLocationName.Items.Add(li);
After you have bound your other data, use:
ddlLocationName.SelectedValue = "-1";
Also, you can add the values of your table in similar way to the ListItem first.

Resources