checkbox list check only limited items - asp.net

I have a list of check boxes and I want to have an upper limit for you many you can check.
Here is what i have done.
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
for (int i = 0; i < chkMultiBrand.Items.Count; i++)
{
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
chkMultiBrand.Items[i].Selected = false;
}
}

I assume if the max number has been exceeded you want to uncheck the last box that was checked so this should work
public void chk_SelectedIndexChanged(object sender, EventArgs e)
{
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (li.Selected)
{
numSelected = numSelected + 1;
}
}
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = control.Length - 1;
ListItem lastChecked = (ListItem) chkMultiBrand.Items[Int32.Parse(control[index])];
lastChecked.Selected = false;
}
}
Although I would possibly try to do this client side if possible - something like this http://jsfiddle.net/CXfgS/2/

If Im reading this correctly as your code stands what yours doing is
Counting the number of checked boxes in the whole list
If the number from the prvious count is greater than the max allowed set everything to false
You need to combine the loops - this isn't perfect as it doesn't track the order in which the items are selected so only the first X number of checkboxes will remain checked and any subsequent items will be unselected.
int numSelected = 0;
foreach (ListItem li in chkMultiBrand.Items)
{
if (numSelected >= Convert.ToInt32(objLimit.UPPERLIMIT))
{
li.Selected = false;
}
if (li.Selected)
{
numSelected = numSelected + 1;
}
}

Related

ASP.NET| checkbox's "checked=true" is not setted in the right checkbox

I'm working on a simple multi-staged registration page for a site I'm building, and I give the user the choice of choosing programs/programming languages he knows using checkboxes:
but when I hit the "next" button, in order to go to the next stage, the checkbox I checked isn't set to true, but checkbox no. 18 is set to true(although I didn't check it)
I'm certain it has something to do with the stage before this one, in which I'm building dynamically radio buttons in which the user is choosing his profession (such as Artist, singer and etc').
there are 17 radio buttons, and they are somehow interfering with the next stage, in which the checkbox's checked values are only starting from checkbox no. 18 as I mentioned earlier.
here is some of the code:
else if (int.Parse(ViewState["DivID"].ToString()) == 2)
{
// save the Birthday Date, Language and country of the user.
ViewState["year"] = int.Parse(DropDownYear.SelectedValue);
ViewState["month"] = int.Parse(DropDownMonth.SelectedValue);
ViewState["day"] = int.Parse(DropDownDay.SelectedValue);
ViewState["Language"] = int.Parse(langDropDown.SelectedValue);
ViewState["Country"] = int.Parse(CountryDropDown.SelectedValue);
// ---------------------------------------------
// change from part 2 of the registration to part 3
registrationP2.Visible = false;
BindProfessions(radios, Page);
registrationP3.Visible = true;
radios.Visible = true;
}
else if (int.Parse(ViewState["DivID"].ToString()) == 3)
{
// change from part 3 of the registration to part 4
ViewState["Profid"] = CheckRadio(radios);
registrationP3.Visible = false;
BindKnowledge(CheckboxCon, Page);
registrationP4.Visible = true;
CheckboxCon.Visible = true;
// ---------------------------------------------
//next.Visible = true;
}
else if(int.Parse(ViewState["DivID"].ToString()) == 4)
{
List<int> v = GetCheckBox(CheckboxCon);
ViewState["Knowids"] = GetCheckBox(CheckboxCon);
}
Binding methods:
public static void BindProfessions(HtmlControl ctrl, Page thispage)
{
List<Profession> Plist = Profession.GetProfessionList();
foreach (Profession p in Plist)
{
HtmlInputRadioButton rd_button = new HtmlInputRadioButton();
const string GROUP_NAME = "Professions";
rd_button.Name = GROUP_NAME;
string LinkID = "P" + p.ProfessionID.ToString();
rd_button.Attributes["id"] = LinkID;
RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
userprofession.imgP = p.ProfPath;
userprofession.fieldName = p.ProfName;
userprofession.IDnum = p.ProfessionID;
userprofession.RadioName = LinkID;
userprofession.EnableViewState = false;
rd_button.EnableViewState = false;
ctrl.Controls.Add(rd_button);
rd_button.Value = p.ProfessionID.ToString();
ctrl.Controls.Add(userprofession);
}
}
public static void BindKnowledge(HtmlControl ctrl, Page thispage)
{
List<Knowledge> Plist = Knowledge.RetKnowledgeList();
foreach (Knowledge p in Plist)
{
HtmlInputCheckBox rd_button = new HtmlInputCheckBox();
const string GROUP_NAME = "knowledge";
rd_button.Name = GROUP_NAME;
string LinkID = "Know" + p.ProgramID.ToString();
rd_button.Attributes["id"] = LinkID;
rd_button.Value = p.ProgramID.ToString();
RegisterUserControl userprofession = (RegisterUserControl)thispage.LoadControl("~/RegisterUserControl.ascx");
userprofession.imgP = p.ProgPath;
userprofession.fieldName = p.PName;
userprofession.IDnum = p.ProgramID;
userprofession.RadioName = LinkID;
userprofession.EnableViewState = false;
rd_button.EnableViewState = false;
ctrl.Controls.Add(rd_button);
ctrl.Controls.Add(userprofession);
}
}
checking methods for both radios and checkbox :
public static int CheckRadio(HtmlControl ctrl)
{
try
{
int counter = 0;
int id = -1;
foreach (Control rdButton in ctrl.Controls)
{
if (rdButton is HtmlInputRadioButton)
{
HtmlInputRadioButton bu = (HtmlInputRadioButton)rdButton;
if (bu.Checked)
{
counter++;
id = int.Parse(bu.Value);
}
}
}
if (counter > 1)
{
return -1;
}
return id;
}
catch (Exception e)
{
return -1;
}
}
public static List<int> GetCheckBox(HtmlControl ctrl)
{
List<int> id_list = new List<int>();
foreach (Control rdButton in ctrl.Controls)
{
if (rdButton is HtmlInputCheckBox)
{
HtmlInputCheckBox bu = (HtmlInputCheckBox)rdButton;
if (bu.Checked)
{
id_list.Add(int.Parse(bu.Value));
}
}
}
return id_list;
}
}
when debugging you can see, that if I choose the first 3 professions, the values returned to me in the List<int> v are 18, 19, and 20
photo: debugging photo
I should mention that after I create the dynamic usercontrols and checkbox/radion buttons, I'm creating them again at postback in protected void Page_Load.
I'm stuck on this for days, and I don't know from where the problem emanates, is it because of ViewState, or the way I'm creating the controls... I really don't know.
Thanks in advance, Idan.
edit:
I played with it a bit, and have found out that when I disable the Binding of the professions which I have initiated earlier in Page_load it does work correctly, page load code look at the second if statement :
protected void Page_Load(object sender, EventArgs e)
{
IsPageRefresh = false;
if (!IsPostBack)
{
ViewState["DivID"] = 1;
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"].ToString();
}
if (int.Parse(ViewState["DivID"].ToString()) == 3)
{
//BindProfessions(radios, Page);
}
else if(int.Parse(ViewState["DivID"].ToString()) == 4)
{
BindKnowledge(CheckboxCon, Page);
}
}
the problem is that I still need to initiate it again after hitting the button in order to get the checked value, how can I fix this thing, and why this is happening? your help would very much be appreciated.
The problem happens because the page recognize that I added 17 new checkbox's, and than when I go over them the first 17 are not checked until the 18'th(the first one of the ones that I checked) what ends up not checking the right checkbox....
And to make it clears I add the other radio buttons to a different div on the page, I don't know what is happening here
for anyone who has the same problem.
I ended up creating the object in Page_PreInit() and it solved the problem, it is recommended(by things I read) to create dynamic objects in Page_PreInit, before anything else is happening to the page.
protected void Page_PreInit(object sender, EventArgs e)
{
try
{
if (!IsPostBack && Session["DivID"] == null)
{
Session["DivID"] = 1;
}
if ((int)Session["DivID"] == 3)
{
InitBindProfessions(Page);
}
else if ((int)Session["DivID"] == 4)
{
InitBindKnowledge(Page);
}
}
catch
{
Response.Redirect("HomePage.aspx");
}
}
InitBindKnowledge and InitBindProfessions are just like BindKnowledge and BindProfession but without adding usercontrols to the control tree

How to hide button according to user login in asp.net

I have some sort of problem to hide the button after any user login. The below snap/image explains my problem:
Check this image
In the above image, you see both user i.e "wajid" and "aamir" have visible of edit button.
Now I want this if "wajid" are login than edit button just show for wajid not for "Aamir".
During Login my session is:
Session["UserName"]
I tried to do this, but it does not work:
string SessionName=Session["UserName"].ToString();
if (SessionName == FirstName)
{
for (int i = 0; i <DealPointsCommentlist1.Items.Count; i++)
{
Edit =(LinkButton)DealPointsCommentlist1.Items[i].FindControl("EditCommentLnkbtn");
Edit.Visible =true;
}
}
else
{
for (int i = 0; i < DealPointsCommentlist1.Items.Count; i++)
{
Edit =(LinkButton)DealPointsCommentlist1.Items[i].FindControl("EditCommentLnkbtn");
}
Edit.Visible = false;
}
Kindly reply me and provide some sort of example.
try this code.
string SessionName=Session["UserName"].ToString();
if (SessionName == FirstName)
{
for (int i = 0; i <DealPointsCommentlist1.Items.Count; i++)
{
LabelName = (Label)DealPointsCommentlist1.Items[i].FindControl("lblFirstName");
if(LabelName.Text == SessionName)
{
Edit = (LinkButton)DealPointsCommentlist1.Items[i].FindControl("EditCommentLnkbtn");
Edit.Visible =true;
}
else
{
Edit =(LinkButton)DealPointsCommentlist1.Items[i].FindControl("EditCommentLnkbtn");
Edit.Visible =false;
}
}
}
else
{
for (int i = 0; i < DealPointsCommentlist1.Items.Count; i++)
{
Edit =(LinkButton)DealPointsCommentlist1.Items[i].FindControl("EditCommentLnkbtn");
}
Edit.Visible = false;
}
Hope It helps.

How to uncheck all checkbox in treeview nodes?

i am working on an application in asp.net.I have used a treeview to show Category.After storing the checked node value into database i want to uncheck all the treeview nodes. for this i have the following code:
foreach (TreeNode node in TreeView1.CheckedNodes)
{
node.Checked=false;
}
but it is showing error:
Collection was modified; enumeration operation may not execute
please help me.
thanks!
foreach is read only and you can't change collection into foreach.
you must use for loop:
for (int i = 0; i < TreeView1.Nodes.Count; i++)
{
TreeView1.Nodes[i].Checked = false;
}
//foreach (TreeNode node in TreeView1.CheckedNodes)
for(int i=0; i<TreeView1.CheckedNodes.Count; i++)
{
TreeNode node = TreeView1.CheckedNodes[i];
node.Checked = false;
}
The CheckedNodes.Count variable is re-evaluated on each pass. So just keep clearing the check box at the 0 index.
int tvCT;
tvCT = TreeView1.CheckedNodes.Count;
if (tvCT > 0)
{
for (int i = 0; i < tvCT; i++)
{
TreeNode node = TreeView1.CheckedNodes[0];
node.Checked = false;
}
}
while (TreeView1.CheckedNodes.Count > 0)
{
TreeView1.CheckedNodes[0].Checked = false;
}
This is a pretty simple block that works for me.
foreach (TreeNode node in TreeView1.Nodes)
{
node.Checked = false;
foreach (TreeNode item1 in node.ChildNodes)
{
item1.Checked = false;
foreach (TreeNode item2 in item1.ChildNodes)
{
item2.Checked = false;
}
}
}
Check it.....! it's work

get sibling controls

Is there some way to find sibling controls / or sibling activity?
In ASP.NET I found a solution by user md1337 solution's, but for WF4 I can't find it.
Thanks a lot.
public static IEnumerable<T> FindVisualChildren<T>(System.Windows.DependencyObject depObj) where T : System.Windows.DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
System.Windows.DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
And in mi Create Activity method I do:
foreach (TextBlock tb in RulesDll.ObjectsClass.FindControls.FindVisualChildren<TextBlock>(target))
{
string a = tb.Text;
}

To get the column Index Of gridview after Databind

what I have done with a grid view is .. According to ma database i have added columns to the datatable and after that i binded it to a gridview.,
here is the code,
/// Get Activities here to bind to GridView To Get the Activities at first Column.
Dt = BlObj.BlDynamic_Table("[USP_DynamicGridView]", 2);
DtOperation = BlObj.BlDynamic_Table("[USP_DynamicGridView]", 1);
for (int i = 0; i < DtOperation.Rows.Count; i++)
{
Dt.Columns.Add(DtOperation.Rows[i][0].ToString());
}
dgrDynamic.DataSource = Dt;
dgrDynamic.DataBind();
but for me needed is to get the column index.. here is the code
private int GetColumnIndexByName(int p)
{
return ((int)GetColumnName(BlObj.BlDynamic_Table("[USP_DynamicGridView]",
4, p).ToString()));
}
private int GetColumnName(string name)
{
foreach (DataColumn col in dgrDynamic.Columns)
{
int Index = 0;
if(col.Equals(name.ToLower().Trim()))
// if (col.Name.ToLower().Trim() == name.ToLower().Trim())
{
return Index;
}
Index += 1;
}
return -1;
}
What the problem is the foreach loop is not working..
I'm a fresher to .NET and I also don't know whether I have followed the right way.. can anybody please help me?
Thanks in advance.
Here's how I did it:
private int GetColumnIndex(GridView gv, string columnName, int columnCount)
{
for (int i = 0; i < gv.Columns.Count; i++)
if (gv.Columns[i].HeaderText == columnName)
return i - columnCount + 1;
throw new Exception("no such column '" + columnName + "'");
}
It works in my codebase.
Use following Function to get Column Index:
private int GetColumnIndexByName(GridView grid, string name)
{
foreach (DataControlField col in grid.Columns)
{
if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim())
{
return grid.Columns.IndexOf(col);
}
}
return -1;
}

Resources