how to check items in checkboxlist? - asp.net

i have a checkboxlist that i want to check some of it's items,
items that i wanna check store in database, i'm selecting them from database and in a loop i wrote thees but just last item selected :(( :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission
where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
int countTags = role.Count();
foreach (string word in role)
{
CheckBoxList1.SelectedValue = word;
Response.Write(word + "<br/>");
countTags -= 1;
}
}
this worked :
var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r)
.FirstOrDefault();
dsRoles.DataBind();
CheckBoxList1.DataBind();
if(selectedRoles != null)
{
string roles = selectedRoles.Roles;
string[] role = roles.Split(',');
foreach (string word in role)
{
try
{
CheckBoxList1.Items.FindByValue(word).Selected = true;
}
catch (Exception exp)
{
lbError.Text= exp.ToString();
}

You will want to select the individual items:
CheckBoxList1.Items.FindByText(word).Selected = true;
or
CheckBoxList1.Items.FindByValue(word).Selected = true;
However, if the checkboxlist doesn't have the text/value you are looking for, it will throw an error.

datatable method checkboxlist
for (int i = 0; i < dt.Rows.Count; i++)
{
chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true;
}

Related

How to use Tempdata to display the list

I have did the excel upload in dotnet core .I had to use tempdata to retrieve the details of the excel in list.Instead in my below code i had used Static object to retrieve the list.My code works as like this ,when i click on upload button it will display the details in the excel sheet.and when click on save it will save it to database and i need to edit in grid view using ajax call also .Help me out
My Action in controller is
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
using (var stream = new FileStream(path, FileMode.Create))
{
await excelfile.CopyToAsync(stream);
}
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
employeesListObject.EmpModelList = employeesViewModelList;
return View(employeesListObject);
}
}
catch(Exception ex)
{
TempData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
Try this, using your own list.
List<string> SomeList = new List<string>();
TempData["MyList"] = SomeList;
//then to get data just do
SomeList = TempData["MyList"] as List<string>; //This converts back to List<T>
Once you add the list to the TempData, you can retrive it from any Action or View in the same controller

ListItem.Selected returning true

I have a CheckBoxList and I am looping through all of it's ListItems's and checking if any one of them are checked.
The strange thing is that although only one of them is checked, it thinks ALL of them are checked.
C# Code:
foreach (ListItem item in cblPermissions.Items)
{
if (item.Selected)
{
// Even though it's not checked on the HTML page - This code still runs.
}
}
This is how I bind the data:
private void BindPermissions()
{
var roles =
RoleInfoProvider.GetAllRoles(
string.Format("RoleName like 'EmployerAdmin[_]%' AND SiteID = {0} AND RoleName NOT LIKE '%Super_User%'",
CMSContext.CurrentSiteID));
cblPermissions.DataSource = roles;
cblPermissions.DataBind();
var userInfo = UserInfoProvider.GetUserInfoByGUID(QueryHelper.GetGuid("guid", Guid.Empty));
if (userInfo != null)
{
var isSuperUser = userInfo.IsInRole(Constants.EmployerAdminSuperUserRole, CMSContext.CurrentSiteName);
if (!isSuperUser)
{
var userRoles = UserInfoProvider.GetUserRoles(userInfo);
foreach (DataRow row in userRoles.Rows)
{
var roleName = row["RoleName"].ToString();
var roleItem = cblPermissions.Items.FindByValue(roleName);
if (roleItem != null)
{
roleItem.Selected = true;
}
}
}
else
{
MarkAllPermissionsAsChecked();
}
}
}
HTML:
<asp:CheckBoxList runat="server" ID="cblPermissions" DataValueField="RoleName" DataTextField="RoleDescription"/>
Any ideas why this is happening?

Cannot implicitly convert type 'System.Linq.IQueryable<Apps.Model.Applicant> to 'Apps.Model.Applicant'. An Explicit conversion Exists ASP.NET MVC3

public ViewResult Index(string currentFilter, string searchString, int? page)
{
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var connString = ConfigurationManager.ConnectionStrings["ApplicantDB"].ConnectionString;
List<Applicant> instructors = new List<Applicant>();
using (var conn = new SqlConnection(connString))
{
conn.Open();
var query = new SqlCommand("SELECT TOP 50 APPLICANT_ID, APPLICANT_Lastname, APPLICANT_FirstName, APPLICANT_MiddleName, APPLICANT_Address, APPLICANT_City"+
" FROM APPLICANT", conn);
var reader = query.ExecuteReader();
int currentPersonID = 0;
Applicant currentInstructor = null;
while (reader.Read())
{
var personID = Convert.ToInt32(reader["APPLICANT_ID"]);
if (personID != currentPersonID)
{
currentPersonID = personID;
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
currentInstructor = new Applicant();
currentInstructor.APPLICANT_ID = Convert.ToInt32(reader["APPLICANT_ID"].ToString());
currentInstructor.APPLICANT_Lastname = reader["APPLICANT_Lastname"].ToString();
currentInstructor.APPLICANT_FirstName = reader["APPLICANT_FirstName"].ToString();
currentInstructor.APPLICANT_MiddleName = reader["APPLICANT_MiddleName"].ToString();
currentInstructor.APPLICANT_Address = reader["APPLICANT_Address"].ToString();
currentInstructor.APPLICANT_City = reader["APPLICANT_City"].ToString();
}
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
}
if (currentInstructor != null)
{
instructors.Add(currentInstructor);
}
reader.Close();
conn.Close();
}
int pageSize = 10;
int pageNumber = (page ?? 0);
return View(instructors.ToPagedList(pageNumber, pageSize));
}
Error in this Line
if (!String.IsNullOrEmpty(searchString))
{
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
}
This is the first time i encountered this type of error . .
I wasted almost 2 hours in this kind of error
I hope someone can help me in this situation. . advance thank you for those who are willing to help. . So much appreciated :) KUDOS !!
As the error says, you are trying to assign single object to list.
currentInstructor = instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()));
If there can be only one result you need to use SingleOrDefault() and if there are multiple records, use FirstOrDefault() which extracts first record from result set.
instructors.AsQueryable().Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper())
|| s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper())).FirstOrDefault();
You probably want the first applicant in the list.
currentInstructor = instructors
.AsQueryable()
.Where(s => s.APPLICANT_Lastname.ToUpper().Contains(searchString.ToUpper()) || s.APPLICANT_FirstName.ToUpper().Contains(searchString.ToUpper()))
.FirstOrDefault();

Build Treeview with parent, child tables

I am building treeview using asp.net 2.0/3.5 from master detail table.
ParentTable Value
---ChildTable Value
---GrandChildTable1 Node
---GrandChildTable1 Value
---GrandChildTable2 Node
---GrandChildTable1 Value
I have created something like this to populate node values. But I am not sure how to display GrandChildNode and values. Could you please let me know if there are any ideas?
Thank you for any help.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
switch (e.Node.Depth)
{
case 0:
GetParentTableValues(e.Node);
break;
case 1:
GetChildTableValues(e.Node);
break;
case 2:
}
}
Here is my solution:
string NodeText = string.Empty;
string NodeKey = string.Empty;
TreeRolesList.Nodes.Clear();
DataTable dtEnqRoles = bllENQRolesMaster.GetENQRolesMasterByRolesDetail();
if (dtEnqRoles.Rows.Count > 0)
{
for (int i = 0; i < dtEnqRoles.Rows.Count; )
{
NodeText = dtEnqRoles.Rows[i]["RoleDescriptionMaster"].ToString().Trim();
NodeKey = dtEnqRoles.Rows[i]["RoleMasterID"].ToString();
TreeNode pNode = new TreeNode(NodeText, NodeKey);
TreeRolesList.Nodes.Add(pNode);
foreach (DataRow dr in dtEnqRoles.Select("RoleMasterID = " + NodeKey))
{
TreeNode childNode = new TreeNode(dr["RoleDescriptionDetail"].ToString().Trim(), dr["RoleDetailID"].ToString());
pNode.ChildNodes.Add(childNode);
i++; //incrementing the outer loop here
}
}
TreeRolesList.ExpandAll();
}

Dynamically add checkboxlist into placeholder and get the checked value of the checkboxlist

I am creating an admin Page, in which checkboxlist(User list from DB)is to be created dynamically and its the checked users value is retrieved.
There are different types of users, so it is distinguised groupwise.
Now first a panel is defined, the checkboxlist is created dynamically and placed inside the panel, then the panel is placed inside a Placeholder.
What Iam doing here is placing the checkboxlist inside the panel, then the panel inside the placeholder. So the values of the Checkboxlist is not retrieved, due to the panel it doesnt get the checkboxlist and it doesn't loop through the Checkboxlist.
What I have done is.
private void AddControl(string pUserGrp, int pUserGrp_Id, int pName)
{
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
User us = new User();
us.OrderBy = "Order By User_Name";
us.WhereClause = "Where UserRole_Id = " + pUserGrp_Id ;
chkList.ID = "ChkUser" + pName ;
chkList.AutoPostBack = true;
chkList.Attributes.Add("onClick", "getVal(ChkUser" + pName + ");");
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
chkList.Attributes.Add("onClick", "getVal(this);");
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
Place.Controls.Add(pUser);
}
private void setChecked(int pPageGroupId)
{
ArrayList arr = new ArrayList();
PageMaster obj = new PageMaster();
obj.WhereClause = " Where PageGroup_Id = " + pPageGroupId;
arr = obj.GetPageGroupUserRights(null);
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
if (chkList != null)
{
for (int i = 0; i < chkList.Items.Count; i++)
{
if (arr.Count > 0)
{
int ii = 0;
while (ii < arr.Count)
{
PageMaster oCand = (PageMaster)arr[ii];
if (oCand.User_Name == chkList.Items[i].Text)
{
if (!chkList.Items[i].Selected)
{
chkList.Items[i].Selected = true;
}
}
ii++;
oCand = null;
}
}
}
}
}
public string GetListCheckBoxText()
{
StringBuilder sbtext = new StringBuilder();
foreach (Control c in Place.Controls)
{
if (c.GetType().Name == "CheckBoxList")
{
CheckBoxList cbx1 = (CheckBoxList)c;
foreach (ListItem li in cbx1.Items)
{
if (li.Selected == true)
{
sbtext.Append(",");
sbtext.Append(li.Value);
}
else
{
sbtext.Append(li.Value);
}
}
}
}
return sbtext.ToString(); }
It doesnt get through the Checkboxlist control in the setChecked(), also doesnt loop through the GetListCheckBoxTest().
Anyone can plz help me.
Regards
The problem is that you are trying to find a control (in setChecked) without setting the Name property. You are using this:
CheckBoxList chkList = (CheckBoxList)Place.FindControl("ChkUser");
But where is this in AddControl?
chkList.Name = "ChkUser";
And in GetListCheckBoxText instead of...
if (c.GetType().Name == "CheckBoxList")
...use this:
if (c.GetType()== typeof(CheckBoxList))

Resources