Checkbox group not detecting if checked - c#

So I am recieving some postback data back from a form and need to get the checkbox values for a group of checkboxes in a parent control. I coded it up and it was working but now no longer works and I can not figure out why. The checkboxes are created on page load dynamically but on postback nothing seems to be checked when the form had checked items, the only postback event is the submit button event.
// This is from the btnSubmit Postback event that isn't working anymore
foreach (CheckBox cb in ShowPermissions.Controls.OfType<CheckBox>())
{
if (cb.Checked)
{
// Add New Admins Permissions
Permission p = new Permission();
p.AdminUserID = au.id;
p.AdminMenuID = Convert.ToInt32(cb.ID.ToString().Substring(4));
ngdb.Permissions.InsertOnSubmit(p);
submitResult.InnerHtml += cb.ID.ToString();
// Does not run now?
}
// can see the checkbox object
}
protected void Page_Load(object sender, EventArgs e)
{
FunctionType = Request.QueryString["func"] != null && Request.QueryString["func"] != "" ? Request.QueryString["func"] : null;
RID = Request.QueryString["rid"] != null && Request.QueryString["rid"] != "" ? int.Parse(Request.QueryString["rid"]) : -1;
PopulateAdminTypes();
if (!IsPostBack && FunctionType == "edit" && RID != -1)
{
// Populate User details for Edit
PopulateUser(RID);
// Populate checkboxes and check selected options
PopulateAdminPermissionOptions(true, RID);
// Disable password change
ChangePassword(false);
}
else if (!IsPostBack)
{
chkChangePassword.Visible = false;
PopulateAdminPermissionOptions(false, -1);
}
}
private void PopulateAdminPermissionOptions(bool blnPopulateForEdit, int RID)
{
// Get Logged in Admin ID
int intAdminId = Convert.ToInt32(Session["AdminID"]);
int intAdminTypeId = Convert.ToInt32(Session["AdminTypeID"]);
using (NewGeorgeDataContext ngdb = new NewGeorgeDataContext())
{
var am = ngdb.AdminMenus.AsQueryable();
// Hide Add and Edit Options from Non Super Users
var amUsers = ngdb.AdminMenus.Where(x => x.id > 2 && x.id < 5);
if (intAdminTypeId > 1) am = am.Except(amUsers);
foreach (var m in am.OrderBy(x => x.MenuTypeID).ThenBy(x => x.id))
{
// Add New CheckBox
CheckBox cb = new CheckBox();
cb.ID = "chk_" + m.id;
cb.CssClass = "chkItems";
cb.Text = m.AdminMenuType.Name + ": " + m.Name;
// Get Admin Permission objects
if (blnPopulateForEdit)
{
var ap = ngdb.Permissions.SingleOrDefault(x => x.AdminUserID == RID && x.AdminMenuID == m.id);
if (ap != null)
{
cb.Checked = true;
}
}
ShowPermissions.Controls.Add(new LiteralControl("<p>"));
ShowPermissions.Controls.Add(cb);
ShowPermissions.Controls.Add(new LiteralControl("</p>"));
}
}
}
Can someone workout what I cannot see atm?

The view state isn't getting load into your controls. You must create all the controls before LoadViewState triggers. So, create all dynamic Controls OnPageInit event or Page_Init method to get the correct behavior. Take a look here to get more information about Asp.NET Page Life Cycle
Hopes this help you!

Related

Select only 1 checkbox or a unique set in Checkboxlist asp net

I need to to use a checkboxlist because there is a unique case the user is allowed to select 3 items at the same time. Problem is that I can't even manage to get the single selection to work. I'm doing this is codebehind with an updatepanel to not refresh the page.
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
int count = 0;
int i = 0;
int maxObjects = cblCodeRequest.Items.Count;
string[] checkObjects = new string[maxObjects];
ListItem selectedItem = new ListItem();
foreach (ListItem item in cblCodeRequest.Items)
{
checkObjects[i] = item.Text;
i++;
}
foreach (ListItem item in cblCodeRequest.Items)
{
if (item.Selected)
{
count++;
selectedItem = item;
cblCodeRequest.ClearSelection();
}
foreach (ListItem itm in cblCodeRequest.Items)
{
if (item.Equals(selectedItem))
{
item.Selected = true;
}
}
}
}
I'm not sure how to proceed from here, i already save the selected item and clear the whole selection and then set it again but it doesn't do it, it just selects itself again after even if i click a different checkbox. I think my logic is messed up
Try this, Your foreach statements are not arranged correctly
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedItem = cblCodeRequest.Items[cblCodeRequest.SelectedIndex]
cblCodeRequest.ClearSelection();
int x = 0;
for(x; x<cblCodeRequest.Items.Count; x++)
{
if (cblCodeRequest.Items[x].Equals(selectedItem))
{
item.Selected = true;
}
}
}
Ok, I finally solved this problem. I had to dig through the problem with the debugger and follow the logic. I did this in jQuery so I can remove the update panel. If Anyone ever gets the same problem as me, this is the solution for you.
This allows you to use a checkboxlist like a radiobuttonlist but also allows you to check multiple checkboxes that belong to a special selection group.
$(function () {
$('[id*=cblCodeRequest] input').on('click', function () {
var checkboxlist = $('[id*=cblCodeRequest]'); // CheckBoxList
var checkboxArray = $('[id*=cblCodeRequest] input'); // CheckBoxList Items
var current = $(this); // Get Selected Checkbox
var label = $(current).next().text(); // Get CheckBox label name
// Uncheck every checkBox that don't match the unique multi selection combo
if (label != "Recâmbio" && label != "Série" && label != "Embalagem Alternativa") {
// Loop through checkboxArray and uncheck every item that does not meet the condition
$(checkboxArray).each(function (i) {
$(this).prop("checked", false);
});
// Check the selected item again
$(current).prop("checked", true);
} else {
// Get the current checkbox name
var chk = $(current).next().text();
// If the checkbox that matches the unique combo selection was click uncheck all invalid checkboxes that don't match
if (chk == "Série" || chk == "Recâmbio" || chk == "Embalagem Alternativa") {
// loop through the checkboxlist again
$(checkboxArray).each(function () {
// Get the looped item name
var ck = $(this).next().text();
// if checkbox does not belong to the unique combo selection, uncheck it
if (ck != "Recâmbio" && ck != "Série" && ck != "Embalagem Alternativa") {
$(this).prop("checked", false);
}
});
}
}
});
});

Grid View check the value is exist?

I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}
You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.

Maintaining session object in webforms

What I am attempting to do is preserve a session object that stores a Dictionary .
I need this dictionary in order to keep a running list that matches up to an asp:Gridview.
Every time the page loads, I'm checking the Dictionary and highlighting any matches in the Gridview.
However, every time Page_Load occurs, the Session["Rolls"] is coming up as null. Now, I'm also highlighting matching entries in a buttonClick event and the Dictionary is preserved up until I initiate a different event (like another button click OR GridView_RowEditing/GridView_RowUpdating). Are there any principals of Session variables that I'm not paying attention to?
Google Chrome console also recognizes the Session throughout every action, but in Debug, every Page_Load brings up a null Session["Rolls"].
Here's my Page_Load code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Rolls"] = new Dictionary<string, int>();
}
else
{
WoSource.SelectCommand =
"SELECT WorkOrderNo, RollNumber, ModelNumber, QtyGood, QtyRun FROM RFID_Inventory WHERE WorkOrderNo= '" + woText.Text + "'";
var currentDict = (Dictionary<string, int>) Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
}
EDIT: Discovered that the RowEditing/RowUpdating events are not preserving the GridView Backcolor highlighting that I'm doing.
Is there something I can add to those event calls?
Here is my RowEditing event:
protected void GridView1_RowEditing(object sender, EventArgs e)
{
var currentDict = (Dictionary<string, int>)Session["Rolls"];
if (currentDict == null)
{
}
else
{
foreach (var entry in currentDict)
{
foreach (GridViewRow row in GridView1.Rows)
{
var dataKey = GridView1.DataKeys[row.RowIndex];
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 0))
{
row.BackColor = System.Drawing.Color.Red;
break;
}
if (dataKey != null && (dataKey["RollNumber"].ToString() == entry.Key && entry.Value == 1))
{
row.BackColor = System.Drawing.Color.Green;
break;
}
}
}
}
}
EDIT2: My issue was solved. My session wasn't coming back null. I actually needed to add my GridView highlighting method to the GridView_RowDataBound event. Turns out I was just trying to highlight the gridview at the wrong time. I marked the Kishore's answer as correct so that users can see my reply. Thanks for everybody's help.
As i look your code you are initialize session variable on page load so you lost the state. you can put a null check before initialize session variable.
Well What we do for managing our Global Object into session is Encapsulating them in Property. Lets have a look in this:
public Dictionary<string, int> Rolls
{
get
{
if(Session["Rolls"] == null)
return new Dictionary<string, int>();
else
return (Dictionary<string, int>)Session["Rolls"];
}
set
{
Session["Rolls"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Now Accessing Rolls in page will be directly hitting Session.
// and Get property will give New dictionary object with 0 record instead of null
// Otherwise it will return Object already caste into dictionary object
foreach (var entry in Rolls)
{
}
// We always can assign new Dictionary object in Session by
Rolls = new Dictionary<string, int>(10); // for example dictionary with 10 items
}
So we can use our Get Set in Parent class of Web page to make it accessible on all child classes. We can use similar approaches for View state and Cache objects as well.
Let me know if you have any question.

How to get the textbox value in ascx page?

In my project I have 3 user controls, those are displayed in master page. When I entered the value in textbox it doesn't getting current value, it will display previous value.
Code:
1st Data Bound:
protected void dlFirstZone_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) && (e.Item.DataItem != null))
{
using (GroceriesServiceClient groceriesServiceClient = new GroceriesServiceClient())
{
HomeMaster pp = (HomeMaster)e.Item.DataItem;
int prdItem = pp.ProductId;
ShoppingCart shopingCartParameter = new ShoppingCart();
//if (pp.DisplayOrder == 1)
//{
Products products = new Products();
if (basePage.BasePageWebSession != null)
{
shopingCartParameter.UserId = Convert.ToInt32(basePage.BasePageWebSession.UserId);
cartlist = groceriesServiceClient.ShoppingCart_UserProductsList(shopingCartParameter);
var td = (from c in cartlist
where c.ProductId == prdItem
select c);
if (td.ToList().Count > 0)
{
TextBox txtQtyDataview = (TextBox)e.Item.FindControl("txtQty");
txtQtyDataview.Text = td.First().Quantity.ToString();
}
}
//}
//else
}
}
}
2nd ItemCommand event handler:
protected void dlProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
HomeMaster q = (HomeMaster)e.Item.DataItem;
if (e.CommandName == "AddToCart")
{
using (GroceriesServiceClient gsc = new GroceriesServiceClient())
{
ShoppingCart shoppingcart = new ShoppingCart();
shoppingcart.UserId = basePage.BasePageWebSession.UserId;
shoppingcart.UserName = basePage.BasePageWebSession.UserName;
shoppingcart.ProductId = Convert.ToInt32(Convert.ToInt32(dlProductDataView.DataKeys[e.Item.ItemIndex]));
TextBox tb1 = (TextBox)e.Item.FindControl("txtQty");
if (!string.IsNullOrEmpty(tb1.Text))
shoppingcart.Quantity = Convert.ToInt32(tb1.Text);
else
shoppingcart.Quantity = 1;
shoppingcart = gsc.ShoppingCart_InsertOrUpdate(shoppingcart);
Response.Redirect(Request.RawUrl);
}
}
}
You can use findControl to find the textbox within a user control, like this (assuming you have a textbox called tb1 in a userconrol called uc1:
me.uc1.findControl("tb1").text
The better way, though, is to expose a public function that can be called to return the value:
In UserControl, create a public function:
public function getValue() as string
return me.tb1.text
end Function
Then you can access it from any page or control that has a reference to the user control:
dim whatsMyName as string = me.uc1.getValue()

"Cannot unregister UpdatePanel with ID 'xxx' since it was not registered with the ScriptManager... " in RadGrid while editing record

Let me cut to the chase. My scenario is as follows: I have custom added fields to filter the RadGrid and filtering works perfectly. The problem comes when I want to edit record using EditForm inside RadGrid. It used to work fine, but then I had some problems with selecting the right row (I was always getting the wrong row selected) so this is what I did to fix it.
So, my RadGrid with filters looks like this:
What I did is to use the Session which will help us to determine later if the filtered RadGrid DataSource was initiated or it was the default one.
protected void btnSearch_Click(object sender, EventArgs e)
{
Session["SearchKontakti"] = "1";
}
After that I had to set PreRender with if loop to check for previously mentioned Session.
protected void gvKontakti_PreRender(object sender, EventArgs e)
{
int idKontakt = Convert.ToInt32(Request.QueryString["idk"]);
if (Session["SearchKontakti"] == "1")
{
var kontakti = from k in db.Kontakt
select k;
int idTipUsera = Convert.ToInt32(rcbTipUsera.SelectedValue);
int idTvrtka = Convert.ToInt32(rcbTvrtka.SelectedValue);
if (rcbTvrtka.SelectedValue != "0")
{
kontakti = kontakti.Where(k => k.idFirma == idTvrtka);
}
if (rcbTipUsera.SelectedValue != "0")
{
kontakti = kontakti.Where(k => k.idOvlasti == idTipUsera);
}
if (chkAktivan.Checked == true)
{
kontakti = kontakti.Where(k => k.Aktivan == true);
}
else
{
kontakti = kontakti.Where(k => k.Aktivan == false);
}
int idAuthKontakt = Convert.ToInt32(Session["authenticatedUI"]);
if (idKontakt > 0 && idAuthKontakt == idKontakt)
{
gvKontakti.DataSource = from k in kontakti
where k.idKontakt == idKontakt
orderby k.Prezime, k.Ime
select new { Tvrtka = k.Firma.Naziv, k.idKontakt, Naziv = k.Ime + " " + k.Prezime, Funkcija = k.Funkcija, k.Ime, k.Prezime, k.Tel1, k.Tel2, k.Mob1, k.Mob2, k.Email1, k.Email2, k.Fax, k.Adresa1, k.Adresa2, k.Adresa3, k.Grad, k.PostanskiBroj, k.Drzava, k.Biljeske, k.Aktivan, k.Username, k.Password };
}
else if (idKontakt > 0 && idAuthKontakt != idKontakt)
{
gvKontakti.DataSource = from k in kontakti
where k.idKontakt == idKontakt
orderby k.Prezime, k.Ime
select new { Tvrtka = k.Firma.Naziv, k.idKontakt, Naziv = k.Ime + " " + k.Prezime, Funkcija = k.Funkcija, k.Ime, k.Prezime, k.Tel1, k.Tel2, k.Mob1, k.Mob2, k.Email1, k.Email2, k.Fax, k.Adresa1, k.Adresa2, k.Adresa3, k.Grad, k.PostanskiBroj, k.Drzava, k.Biljeske, k.Aktivan, k.Username, k.Password };
}
else
{
gvKontakti.DataSource = from k in kontakti
orderby k.Prezime, k.Ime
select new { Tvrtka = k.Firma.Naziv, k.idKontakt, Naziv = k.Ime + " " + k.Prezime, Funkcija = k.Funkcija, k.Ime, k.Prezime, k.Tel1, k.Tel2, k.Mob1, k.Mob2, k.Email1, k.Email2, k.Fax, k.Adresa1, k.Adresa2, k.Adresa3, k.Grad, k.PostanskiBroj, k.Drzava, k.Biljeske, k.Aktivan, k.Username, k.Password };
}
gvKontakti.DataBind();
}
}
So, this fixed my primary problem, but gave me another one. Some of my UserControls contain UpdatePanel and for each UserControl that has it whenever I try to clik Edit button from the RadGrid I receive the following message: "Cannot unregister UpdatePanel with ID 'UpdatePanel4' since it was not registered with the ScriptManager. This might occur if the UpdatePanel was removed from the control tree and later added again, which is not supported.
Parameter name: updatePanel"
What I'd like to know is how to fix it.
Regards,
Hrvoje
I don't know why, but somehow the UpdatePanel is unregistered from the ScriptManger twice (it happens in RadGrid.Rebind() method too; the situation I was stuck in), and the second time it's unregistered from ScriptManger you get the "Cannot unregister UpdatePanel ..." error.
The workaround is to register the UpdatePanel with the ScriptManger somewhere between the two unregister events, using reflection, like this:
protected void UpdatePanel_Unload(object sender, EventArgs e) {
MethodInfo methodInfo = typeof(ScriptManager).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(i => i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First();
methodInfo.Invoke(ScriptManager.GetCurrent(Page),
new object[] { sender as UpdatePanel });
}
you should add the UpdatePanel_Unload to the OnUnload event of the UpdatePanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
You can find the complete details of the problem here
Protected Sub UpdatePanel_Unload(ByVal sender As Object, ByVal e As EventArgs)
Dim methodInfo As MethodInfo = GetType(ScriptManager).GetMethods(BindingFlags.NonPublic Or BindingFlags.Instance).Where(Function(i) i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First()
methodInfo.Invoke(ScriptManager.GetCurrent(Page), New Object() {TryCast(sender, UpdatePanel)})
End Sub
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
I had this issue as well.. when turning off pahing on the grid to to the export to EXCEL.
I changed the rebind to be on the mastertableview
ie
RadGrid1.MasterTableView.AllowPaging = false;
RadGrid1.MasterTableView.Rebind();
instead of
RadGrid1.MasterTableView.AllowPaging = false;
RadGrid1.Rebind();
In case someone else had this...

Categories