FormView_Load being overwritten C# ASP.NET - c#

I've got a formview whose load event just decided to stop working. I did some debugging and noticed that it was reaching the code, but for whatever reason, the attributes that I am adding in the load event are no longer displaying on the screen. It's as if something is happening after the formview's load event that is reloading it without any of my extra attributes. The only modification that I have done before it stopped working is that I added a session variable in the page before it. That should not cause such a drastic change.
Here is my code:
protected void FormView1_Load(object sender, EventArgs e)
{
RadioButton rbinjury = (RadioButton)FormView1.FindControl("rbinjury");
RadioButton rbproperty = (RadioButton)FormView1.FindControl("rbproperty");
RadioButton rbboth = (RadioButton)FormView1.FindControl("rbboth");
RadioButton rbyes = (RadioButton)FormView1.FindControl("rbyes");
RadioButton rbno = (RadioButton)FormView1.FindControl("rbno");
RadioButton rbyes2 = (RadioButton)FormView1.FindControl("rbyes2");
RadioButton rbno2 = (RadioButton)FormView1.FindControl("rbno2");
RadioButton rbam = (RadioButton)FormView1.FindControl("rbam");
RadioButton rbpm = (RadioButton)FormView1.FindControl("rbpm");
TextBox txtdate = (TextBox)FormView1.FindControl("txtdate");
DropDownList ddlhour = (DropDownList)FormView1.FindControl("ddlhour");
DropDownList ddltime = (DropDownList)FormView1.FindControl("ddltime");
if (FormView1.CurrentMode == FormViewMode.Insert || FormView1.CurrentMode == FormViewMode.Edit)
{
txtdate.Attributes.Add("onfocus", "unfocus();");
locList.Attributes.Add("onChange", "postBack();");
ddlhour.Items.Insert(0, new ListItem("Hour", "0"));
ddlhour.Items.Insert(1, new ListItem("12", "12"));
ddltime.Items.Insert(0, new ListItem("Minute", "0"));
for (int i = 1; i < 12; i++)
{
String hour = Convert.ToString(i);
ddlhour.Items.Add(new ListItem(hour, hour));
}
for (int i = 0; i < 61; i++)
{
String time = "";
if (i < 10)
{
time = ":0" + Convert.ToString(i);
}
else
{
time = ":" + Convert.ToString(i);
}
ddltime.Items.Add(new ListItem(time, time));
}
//-----------------------------------------handle radio buttons----------------------------------------------------------------
rbinjury.Attributes.Add("Onclick", "radio('rbinjury','result');");
rbproperty.Attributes.Add("Onclick", "radio('rbproperty','result');");
rbboth.Attributes.Add("Onclick", "radio('rbboth','result');");
rbyes.Attributes.Add("Onclick", "radio('rbyes','inj');");
rbno.Attributes.Add("Onclick", "radio('rbno','inj');");
rbyes2.Attributes.Add("Onclick", "radio('rbyes2','dmg');");
rbno2.Attributes.Add("Onclick", "radio('rbno2','dmg');");
rbam.Attributes.Add("Onclick", "radio('rbam','time');");
rbpm.Attributes.Add("Onclick", "radio('rbpm','time');");
}}
Any idea what would cause the load event to stop working? If I place this same code in the page's save state complete event, it does work, but I should not have to...

you need to use formview Databound event instead of formview load event to set values, try
using this
protected void frm_DataBound(object sender, EventArgs e)
{
if (frm.CurrentMode == FormViewMode.Edit)
{
TextBox txtdate = (TextBox)frm.FindControl("txtdate");
txtdate.Attributes.Add("", "");
}
}
Also check these threads.
ASP.NET Can not Change Visibility of a Formview control
FormView.FindControl(): object reference error

Related

C# Listboxes using selectedvaluechanged

I usually figure things out but this has me beat.
I have an array of listboxes on a form and a submit button. The user can pick items from any listbox then click the submit button to choose the confirm the item, but what needs to happen is that if they select something from listbox 1 then change their mind and select something from listbox 2, the item selected in listbox 1 should become unselected.
I can code that in to the eventhandlers but the problem is as soon as I change a value in another listbox programatically it fires another event. I can't seem to logic my way out of it.
Any ideas would be great otherwise I guess I will just have to put multiple submit buttons.
EDIT:
I figured out what I think is quite an obvious and simple solution in the end. I made use of the focused property to distinguish whether the user or the program was making changes. Works for both mouse and keyboard selections.
Thanks for the suggestions...
for (int i = 0; i < treatments.Length; i = i + 1)
{
this.Controls.Add(ListBoxes[i]);
this.Controls.Add(Labels[i]);
this.Controls.Add(Spinners[i]);
Labels[i].Top = vPosition - 20;
Labels[i].Left = hPosition;
Labels[i].Width = 600;
ListBoxes[i].Left = hPosition;
ListBoxes[i].Top = vPosition;
ListBoxes[i].Width = 600;
Spinners[i].Top = vPosition + ListBoxes[i].Height;
Spinners[i].Left = hPosition + ListBoxes[i].Width - 60;
Spinners[i].Width = 40;
for (int d = 25; d > 0; d = d - 1) { Spinners[i].Items.Add((d).ToString()); }
Spinners[i].SelectedIndex = 24;
//EVENT HANDLER CODE that is executed if any selectetindexchange in any LIstbox in array
ListBoxes[i].SelectedIndexChanged += (sender, e) =>
{
for (int s = 0; s < i; s = s + 1)
{
//FIND WHICH LBs[s] IS THE SENDING LISTBOX
if (ListBoxes[s] == sender && ListBoxes[s].Focused == true)
{
string msg = "sender is ListBox " + s.ToString() + "\nFocus is" + ListBoxes[s].Focused.ToString();
// MessageBox.Show(msg);
}
else if(ListBoxes[s].Focused==false)
{
ListBoxes[s].SelectedIndex = -1;
}
}
}; //end of event handler
}
I generally solve this kind of problem with a flag that lets me know that I am changing things, so my event handlers can check the flag and not take action in that case.
private int codeChangingCount = 0;
private void combobox1_SelectedIndexChanged(object sender, EventArgs e) {
codeChangingCount++;
try {
combobox2.SelectedIndex = someNewValue;
} finally {
codeChangingCount--;
}
}
private void combobox2_SelectedIndexChanged(object sender, EventArgs e) {
if (codeChangingCount == 0) {
//I know this is changing because of the user did something, not my code above
}
}
You can do this with a simple bool instead of an int, but I like the counter approach so that I can keep incrementing codeChangingCount in nested calls and not accidentally reset it. In my production code, I have a class dedicated to this kind of flagging, and it (mis)uses IDisposable to decrement, so I can just wrap my calls in a using block, but the above snippet is simpler for illustration.
Check if Focused ListBox == ListBox2 and SelectedIndex > -1 then deselect Index[0]
if (ListBoxes[s] == sender && ListBoxes[s].Focused == true)
{
if(s == 1 && ListBoxes[s].SelectedIndex > -1) //assuming 1 is listbox2
{
ListBoxes[0].SelectedIndex = -1; // Deselect ListBox1
}
string msg = "sender is ListBox " + s.ToString() + "\nFocus is" + ListBoxes[s].Focused.ToString();
}

Events not firing on the first postback, but will fire after that

I'm having quite a strange issue where my generated control will not fire its' SelectedIndexChanged event on the first click, but will dutifully work after that.
The code is as follows:
//Generate list
ddl.Items.Add(new ListItem(" ", " "));
for(int i =1 ; i < 13 ; i ++)
{
ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
//ddl.SelectedIndex = -1;
tc2.Controls.Add(ddl);
tr.Cells.Add(tc2);
//Keep position after postback
for (int i = 1; i < 13; i++)
{
if (i.ToString() == sNoOfPreviousMonths )
{
ddl.SelectedIndex = i;
}
}
And the event:
void ddlNoOfPreviousMonths_SelectedIndexChanged(object obj, EventArgs e)
{
DropDownList x = obj as DropDownList;
sNoOfPreviousMonths = x.SelectedValue;
}
I found out the answer, turns out that on the first click the control's ID is different, and gets changed on the second click. It's explained better here
i think u dont use Autopostback for dropdownlist. u need set to be true value

How to get checkbox value in gridview

Can you please help me on this, I get the check box control value as false always even when I check the control in gridview.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox CheckBox1 = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox1 != null)
{
if (CheckBox1.Checked)
{
query = GridView1.Rows[i].FindControl("Label1") + ",";
}
}
}
Are you databinding on Page_Load method? If yes, you must do this:
if(!IsPostBack)
{
GridView1.DataSource = YourData;
}
If you don't do this, your DataGridView will be databound even if it is a PostBack. This way no matter what you checked, the DataGridView will be repopulated from the data source for your postbacks.
Using the above code, when you do if(!IsPostBack), it will retain the checkbox's viewstate value and you get the correct Checked status.
Inside the checkbox design add the following attribute
ToolTip="<%#Container.DataItemIndex+1 %> " and then following is the code behind
for (int i = 0; i < gdview.Rows.Count; i++)
{
string labeldetail = "";
CheckBox cbox = (CheckBox)gdview.Rows[i].Cells[0].FindControl("CheckBox1");
if (cbox != null)
{
if (cbox.Checked == true)
{
int rowsNo = (Convert.ToInt16(city.ToolTip) - 1); //Convert.ToInt16(SrNo);
labeldetail = ((Label)gdview.Rows[rowsNo].FindControl("labelid")).Value;
}

get dynamic checkbox value on button click

i have a page where i create 2 checkboxes dynamically.
TableRow tr = new TableRow();
for (int i = 0; i < 2; i++)
{
TableCell Tc = new TableCell();
Tc.Attributes["style"] = "line-height: 30px; text-align: left";
Tc.Attributes["width"] = "50%";
Tc.Style.Add("padding-left", "5px");
//Checkboxes on left along with labels
CheckBox checkBoxCtrl = new CheckBox();
checkBoxCtrl.ID = "checkBoxCtrl" + i;
Tc.Controls.Add(checkBoxCtrl);
tr.Cells.Add(Tc);
}
once they are created in the page load event i have a Ok_button click event which requires to check if the checkbox is checked or not.
protected void Update2_Click(object sender, EventArgs e)
{
if(checkBoxCtrl.checked)
//here i wont be able to get the value
// i get the error the name checkBoxCtrl does not exist..
{
response.write("true");
}
}
but how do i do the check in this case.
thanks
Answer:
this is what needs to be done to get the checkbox values
protected void Update1_Click(object sender, EventArgs e)
{
for(int i = 0; i < ControlPropList.Count; i++)
{
CheckBox chkTest = (CheckBox)xxx.FindControl("checkBoxCtrl" + i);
{
if (chkTest.Checked)
{
Global.logger.Info("Checkbox True = " + chkTest.ID);
}
else
{
Global.logger.Info("Checkbox False = " + chkTest.ID);
}
}
}
}
This should work fine as long as you add the checkboxes to your page in the Page_PreInit method. If you add them after that (Page_Load for example), their values will not be maintained.
Read about the asp.net page lifecycle here:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Consider storing the dynamic checkbox in a local member:
private CheckBox _myCustomCheckbox = new CheckBox();
protected override void OnInit(EventArgs e)
{
TableRow tr = new TableRow();
for (int i = 0; i < 2; i++)
{
TableCell Tc = new TableCell();
if (i == 0)
{
Tc.Attributes["style"] = "line-height: 30px; text-align: left";
Tc.Attributes["width"] = "50%";
Tc.Style.Add("padding-left", "5px");
//Checkboxes on left along with labels
_myCustomCheckbox.ID = "checkBoxCtrl" + j;
Tc.Controls.Add(_myCustomCheckbox);
tr.Cells.Add(Tc);
}
}
// the row needs added to a page control so that the child control states can be loaded
SomeTableOnThePage.Controls.Add(tr);
base.OnInit(e);
}
protected void Update2_Click(object sender, EventArgs e)
{
if(_myCustomCheckbox.Checked)
{
response.write("true");
}
}
May not be quite what you want, but I had a similar issue, I have a dynamically generated table in ASP.NET page, with dynamically generated CheckBoxes in one column. I have created the data for the table from a collection, and then as the dynamic CB's are created I give them an ID and store them in a second collection, such as an array of CB's.
So when I need to find the Checked value I simply iterate through the collection, and I can find the ones that are Checked.
Also as they were created simultaneously with the data in the dynamic table I was able to easily tie the table data row to the Checkbox value.
This obviously assumes that the dynamic table and CB's were created using some kind of looping.
This may not be the best solution but works for my current needs.

display a particular number from dropdownlist

Is there a way in dropdownlist to show the desired number on pageload?
eg.
I have a dropdownlist control
I am using a for loop to populate it
for (int i = 1; i <= 100; i++)
{
DropDownList1.Items.Add(i.ToString());
}
Now this displays 1 on page load ... but I want to display 7..
How do I do that?
If you mean that it is the default selected value, you would just need to set a default selected value in the page load, after the list has been populated. Make sure only to do this when it is not a postback or you will overwrite any user selections.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "7"
}
}
Would set it inside your for loop. Would also store the default somewhere outside the code (db, config) so if it changes you don't have to redeploy.
if(!IsPostBack)
{
for (int i = 1; i <= 100; i++)
{
var newItem = new ListItem(i.ToString());
newItem.Selected = (i == 7);
DropDownList1.Items.Add(newItem);
}
}
After your for loop
DropDownList1.Items.FindByText("7").Selected = true;
Use the SelectedItem or SelectedIndex property.

Categories

Resources