Nested Foreach Loop not working? - asp.net

I have 2 datagrids. Both with checkboxes. I have a nested foreach loop that gets the DataKeys values of both checked persons from both datagrids. When I run the debugger the first datakey gets assigned to the correct variable oIdividualID. That is working fine. The second foreach loop gets the datakey from the next datagrid. That works fine too. However, it is not assigning it to the variable oNewParentID. and At the bottom of my code, in debugging, the method I am calling holds the value of oIndividualID correctly, But oNewParentID Holds NO value? Is there something wrong with my nested foreach loop? I don't understand. Here's my code:
protected void imgbtnReassgin_Click(object sender, ImageClickEventArgs e)
{
foreach (GridViewRow row in gvAdminCustomer.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkitemSelectorCustomers");
if (cb != null && cb.Checked)
{
int oIndividualID = Convert.ToInt32((gvAdminCustomer.DataKeys[row.RowIndex].Value));
foreach (GridViewRow r in gvReassignCustomers.Rows)
{
CheckBox chkBox = (CheckBox)row.FindControl("chkitemSelectorAllManagersandSalesman");
if (chkBox != null && chkBox.Checked)
{
int oNewParentID = Convert.ToInt32((gvReassignCustomers.DataKeys[r.RowIndex].Value));
Individual ind = new Individual();
ind.ReassignIndividual(oIndividualID, oNewParentID);
}
}
gvReassignCustomers.DataBind();
gvAdminCustomer.DataBind();
}
}
}

hard to understand the purpose of the code - for every checked tickbox in Admin grid you're running reassign on every checked Reassign grid. Is it really the intent?
And then you're running DataBind() for every line on in admin grid.
So.
Comment out DataBind() - you don't need them there, it's just tells the system to rebind the data to the grids which can potentially clear the user ticked tickboxes.

Not quite sure what happened, but suddenly it all started working. Problem solved but not sure how.

Related

How do I set a default value of 0 to a radtextbox in a radgrid if the value is null after databind?

i have a series of radtextboxes as columns in a radgrid. The data they pull is often null. I'd like them to have a default value of zero in those cases. How do i accomplish this?
I tried this without success:
protected void rGrid_Inductions_PreRender(object sender, EventArgs e)
{
foreach (GridDataItem item in rGrid_Inductions.Items)
{
foreach (Control ctr in item.Controls)
{
if (ctr.GetType() == typeof(RadTextBox))
{
(ctr as RadTextBox).Text = "0" + (ctr as RadTextBox).Text;
}
}
}
rGrid_Inductions.Rebind();
}
Appreciate the help
why dont u just set the Default Text of RadTextBox=0 when you creating them and then in this (prerender loop) modify them if they are not null;
You can definitely set the Default value when you drop the control on the page if you are creating the Control on Design View or on code behind http://www.telerik.com/help/aspnet-ajax/input-textbox-basics.html
Im puzzled as to why do you concatenate the text with the
(ctr as RadTextBox).Text = "0" + (ctr as RadTextBox).Text;
Is the 0 supposed to be permanent regardless of the text? Can you show me a sample Text?
However if all you want is the 0 as default, all you have to do is assign the value on design time or code behind like in the documentation that I posted above.

why my view state not getting cleared and on reload it save the value to the databse again?

I am having user control registered on a aspx page.
there is a button on user control resisted on some aspx page that perform some action to store the value of viewste to the database, and below that i have cleared my viewstate value, but if i do right click and reload the page it reinsert the values to the data base, what i am missing or the viewstate do not get cleared, how should i prevent it to resave the same entries to the database.
I am partially writing my code below.
protected void btnFinish_Click(object sender, EventArgs e)
{
if (ViewState["dtQuestions"] != null)
{
foreach (DataRow dr in dtQuestions.Rows)
{
int currQueScore = GetAnswerScore(dr["AnswerType"].ToString().Trim(), dr["ClientAnswerValue"].ToString().Trim());
dr["ClientAnswerScore"] = currQueScore;
myScore += currQueScore;
SurveyClientAnswer objDetail = new SurveyClientAnswer();
objDetail.SurveyClientID = objMaster.SurveyClientID;
objDetail.QuestionID = int.Parse(dr["QuestionID"].ToString());
objDetail.Answer = dr["ClientAnswerValue"].ToString();
objDetail.Score = int.Parse(dr["ClientAnswerScore"].ToString());
DB.SurveyClientAnswers.InsertOnSubmit(objDetail);
DB.SubmitChanges();
}
objMaster.FinalScore = myScore;
DB.SubmitChanges();
ViewState["dtQuestions"] = null;
}
else
{
ModalPopupExtender1.Show();
pnl.Visible = true;
}
}
If you don't want to reinsert the data, simply create a unique constraint on the database to disallow this scenario.
As far as doing it in code, you could possibly only insert the data adding this condition to the if statement:
if(IsPostBack && (ViewState["dtQuestions"] != null)
{
//meaning the user is not simply reloading the page but actually posting back
}
Note that there might be some corner cases where this won't work. Without testing is difficult to know but I strongly believe that this should be handled at the database level instead.

Gridview cell value and array list

When I am tryng to pass the gridview cell values to an array everything is perfect but the array is empty after executing the code.
When I see through debug mode the index of selected row also is fine, i.e. when I select two rows using checkbox among 1000 the count shows exactly 2 in the array but the data is empty.
I'm not able to get the cell value from the gridview.
Any advice would be greatly appreciated.
protected void Button2008_Click(object sender, EventArgs e)
{
ArrayList checkedItems = new ArrayList();
foreach (GridViewRow row in this.GridView1.Rows)
{
if (((CheckBox)row.FindControl("cbRows")).Checked == true)
{
checkedItems.Add(row.Cells[12].Text);
}
}
Session["CheckedItems"] = checkedItems;
Response.Redirect("About.aspx", true);
}
you can use a breakpoint and check where the problem is occuring, for instance, does row.Cells[12].Text show any value ?
and you can check how your aspx page is acting after the postback.

How can I retrieve a subset of data from entity object data source and pass to another page

I am playing about just now trying to teach myself a little bit about the entity framework.
I have a Gridview data bound to a Entity Date Source using the Entity Framework. If I select certain items in that list I then wish to redirect another page and populate another gridview with just the items selected (but with more detail, different includes/navigation properties)
This is probably the most simple thing but I have spent 2 hours banging my head on the wall trying to get this to work.
Essentially I have a continue button which when clicked should identify all the UIDs (a column in the gridview) of the rows and allow me to subset to just these rows and pass them to another page to be rebound to another datagrid
Any ideas???
Well, the big picture is that you should get those IDs, pass them to the other page, and then use a query with Contains; see this question for an idea of how to use it:
How search LINQ with many parametrs in one column?
Assuming you haven't used DataKeys in your GridView, this would be my approach.
Page 1
protected void Button1_Click(object sender, EventArgs e)
{
var checkedItems = new List<int>();
foreach (GridViewRow row in GridView1.Rows)
{
var checkbox = (CheckBox)row.FindControl("CheckBox1");
if (checkbox.Checked)
{
checkedItems.Add(int.Parse(row.Cells[1].Text));
}
}
Session["checkedItems"] = checkedItems;
Response.Redirect("Page2.aspx");
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
var checkedItems = (List<int>)Session["checkedItems"];
Session["checkedItems"] = null;
foreach (var checkedItem in checkedItems)
{
Response.Write(checkedItem);
}
}
Using the IDs in the checkedItems List you can now query those from you DB and finally assign the Result to your GridView on the second page.
Instead of using Session you could pass the IDs via QueryString.

Accessing asp.net tablerow child control by type

I'm iterating through a collection of asp:tablerows to be able to get or set the text in a textbox that is nested in the third cell of the row; I'm doing this by type rather than by ID because the cell ID's in that column aren't totally consistent--thus I can't really call FindControl() to achieve this. I've resorted to casting the third control in the TableRow to a TableCell and then Casting the first control in that cell to a TextBox. Not quite correct, as I'm getting an index out of range exception thrown. The problem mainly lies in the Controls.Count() property of the third cell, which comes to zero.
Not sure if there's a better way to access the textbox---should I resort to FindControl()?
The code:
foreach (TableRow row in tblProviders.Rows) {
string value = ((TextBox)((TableCell)row.Controls(2)).Controls(0)).Text;
...
}
My searches here only yielded use of FindControl(), so that may be the only way...
Thanks!
You could use Linq as follows:
var TextBoxes = tblProviders.Rows.OfType<TableRow>()
.SelectMany(row => row.Cells.OfType<TableCell>()
.SelectMany(cell => cell.Controls.OfType<TextBox>()));
TextBoxes would then be a collection of all the textboxes in tblProviders.Rows, which you could then itterate through and do what you like with.
A little bit of null checking wouldn't go amiss here.
You could try using this Recursive call:
foreach (TableRow row in tblProviders.Rows) {
var tb = FindControlRecursive(row, typeof(TextBox));
if (tb != null) {
string value = ((TextBox)tb).Text;
}
}
private Control FindControlRecursive(Control rootControl, Type controlType) {
if (rootControl.GetType() == controlType)
return rootControl; //Found it
foreach (Control controlToSearch in rootControl.Controls) {
Control controlToReturn = FindControlRecursive(controlToSearch, controlType);
if (controlToReturn != null) return controlToReturn;
}
return null;
}

Resources