Selected Index changed doesnt fire - asp.net

I have a drop down list that is populated on page load and by default the selected index is 0 and its set to an emty string. On page load if we change the selected value the selected index method doesnt fire.
if(!page.isPostback)
{
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.selectedIndex = 1;
this.ddl.SelectedValue = Id.ToString();
}
}

That's as it should be. If you want to execute some piece of logic from both the event and/or from page load, put that logic in a separate method so you can call it easily from your page load.

private void BindList()
{
this.ddl.Items.Clear();
this.ddl.DataSource = list;
this.ddl.DataValueField = "Id";
this.ddl.DataTextField = "Name";
this.ddl.DataBind();
this.ddl.Items.Insert(0, String.Empty);
this.ddl.Items.SelectedIndex = 0;
}
if(!page.isPostback)
{
BindList();
if (Request.QueryString != null)
{
string name = Request.QueryString["name"];
long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault();
this.ddl.Items.ClearSelection();
this.ddl.Items.FindByValue(Id.ToString()).Selected = true;
}
}

Related

asp:DropDownList doesn't return correct value

I have this DropDownList I bind it on the codebehind, when I put on IsPostBack always return null and when I put out always return the first value.
The code is this one:
if (!IsPostBack)
{
preencherAreas();
}
public void preencherAreas()
{
try
{
string[] areas = areaLocal.Area.Split(';');
List<Area> listAreas = new List<Area>();
foreach (var a in areas)
{
listAreas.Add(new Area(a, a.Replace(" ", "_")));
}
selectArea.DataSource = listAreas;
selectArea.DataTextField = "Text";
selectArea.DataValueField = "Value";
selectArea.DataBind();
}
catch (Exception)
{
}
}
I try to catch the value wit SelectedValue and with SelectedItem.Value and the result is always the same that I said

dropdown values according to rights

There is multiple values in that dropdown ..
e.g.
Car
Truck
Bike
Drink
Factory
There is another login page Login.aspx .
Login code
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Label1.BackColor = "F8D8D7";
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("WebForm1.aspx");
}
catch( Exception )
{
Label1.Text = ("Incorrect UserName/Password");
Label1.Visible = true;
}
txt_us.Text = "";
txt_pwd.Text = "";
}
public bool loginmethod(string UserName,string Password)
{
TrackDataEntities1 td = new TrackDataEntities1();
splogin1_Result sp = td.splogin1(UserName, Password).FirstOrDefault();
if(sp.Password==txt_pwd.Text)
{
return true;
}
else
{
return false;
}
}
Now there is two users .. admin and user . Now i want when admin login then with their id and password then he see some values from this list and when user login then he will see some values from this list for example when admin login then he may able to see only Factory value and when user login then he able to see all values except factory
UPDATE
in login.aspx i save username is session
Session["UserName"] = txt_us.Text;
in form.aspx
Here first i create sp
ALTER procedure [dbo].[spadminlist]
as
select Region from tblReg
where Region in ('Factory')
then i add this sp in form.aspx
//this linq query for selecting all values
var list = tea.tblReg.AsEnumerable()
.Where(x => !x.Region.Any(char.IsDigit) && (x.Region != ""))
.GroupBy(x => x.Region)
.Select(x => new { Region = x.Key, Value = x.Key })
.ToList();
//this is for admin
if (Session["UserName"] = "admin")
{
List<spadminlist_Result> admin = tea.spadminlist().ToList();
}
and filling dropdown
if (!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "Region";
regiondrop.DataValueField = "Region";
regiondrop.DataBind();
Label4.Visible = false;
}
but this show error and also how i fill dropdown with admin sp because there is queries
Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?)
how i do this ?
For Dynamic list:
Get from the backend whether user is admin or normal user.
List<string> menuItems = new List<string>();
if(logged_user == "ADMIN")
{
menuItems.add("item1");
menuItems.add("item2");
}
else
{
menuItems.add("item1");
menuItems.add("item2");
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = menuItems;
DropDownList1.DataBind();
For Static list:
if(logged_user == "ADMIN")
{
DropDownList1.Items.FindByText("Item1").Enabled = false;
OR
DropDownList1.Items[i].Enabled = false;
}
else
{
Same process as above.
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataBind();

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?

How to maintain state in (asp.net) custom server control?

I am trying to make a custom server control which inherits from DropDownList. I give the control an XML input containing some key/value pairs and my control shows them as a DropDownList.
I make the list items in the override Render method like this:
foreach (XElement child in root.Elements("Choice"))
{
string title = child.Element("Title").Value;
string score = child.Element("Score").Value;
item = new ListItem();
item.Text = title;
item.Value = score;
this.Items.Add(item);
}
The problem is that, when the user selects and item in the list, and the page posts back, the selected item is lost, and the list is re-initialized with the default data.
Does anyone have any idea how to keep the selected item, i.e. maintain the state?
Here is the complete source:
public class MultipleChoiceQuestionView2 : DropDownList
{
public MultipleChoiceQuestionView2() : base()
{
}
protected override void Render(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
#region Parse Contets
if (!String.IsNullOrEmpty(this.Contents))
{
XElement root = XElement.Parse(this.Contents);
if (root.HasAttributes)
{
this.NoOfChoices = Int32.Parse(root.Attribute("ItemCount").Value);
}
this.Items.Clear();
this.Style.Add("width", "100px");
this.Style.Add("font-family", "Tahoma");
this.Items.Clear();
ListItem item = new ListItem();
item.Text = "";
item.Value = "0";
this.Items.Add(item);
foreach (XElement child in root.Elements("Choice"))
{
string title = child.Element("Title").Value;
string score = child.Element("Score").Value;
item = new ListItem();
item.Text = title;
item.Value = score;
this.Items.Add(item);
}
}
#endregion
base.Render(writer);
writer.RenderEndTag();
if (this.Required)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = this.ID;
rfv.InitialValue = "0";
rfv.Text = "*";
if (!String.IsNullOrEmpty(this.ValidationGroup))
{
rfv.ValidationGroup = this.ValidationGroup;
}
writer.RenderBeginTag(HtmlTextWriterTag.Td);
rfv.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.RenderEndTag();
}
#region Properties
public string Contents
{
get
{
return ViewState["Contents"] == null ? "" : ViewState["Contents"].ToString();
}
set
{
ViewState["Contents"] = value;
}
}
private int mNoOfChoices;
public int NoOfChoices
{
get
{
return mNoOfChoices;
}
set
{
mNoOfChoices = value;
}
}
private string mValidationGroup;
public string ValidationGroup
{
get
{
return mValidationGroup;
}
set
{
mValidationGroup = value;
}
}
public string SelectedChoice
{
get
{
return "";
}
}
private bool mRequired = false;
public bool Required
{
get
{
return mRequired;
}
set
{
mRequired = value;
}
}
#endregion
}
Thanks in advance.
You've got two options: ViewState or ControlState.
The difference being ViewState can be overriden by setting EnableViewState="false" in the page directive, whilst ControlState cannot.
Essentially you need to hook into the state bag when you're getting/setting the values of the dropdown.
There's a decent example here where a custom control is derived from the Button class and maintains state between page requests - should fit your scenario nicely.
Hopefully that gets you started.

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