Textbox value null when trying to access it - asp.net

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}

Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.

You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

Related

Incrementing variables in ASP.net on every button click

I want to increment date in every click ASP.NET.
But Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0.
I need to persist a value across postbacks but I don't how to do that. I would appreciate for any help.
Here is what I'am trying to do:
int myNumber = 0;
protected void Button1_Click1(object sender, EventArgs e)
{
lblDate.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(myNumber).ToShortDateString();
myNumber++;
}
Update:
My finaly goal is to get next weeks first day with next button and Previous week, I mean I want to forword and backword...
public int NextCount
{
get { return ViewState["Count"] != null ? (int)ViewState["Count"] : 7; }
set { ViewState["Count"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount+7;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
NextCount = NextCount - 7;
}
But When I click Prev button .. there is delay with one click after two or three Click then reaction coming the same with next button when you click from prev to next. Maybe I have to store it in session?
I have updated your code below by using ViewState to handle this. Other easiest option would be storing the same in Session, Cache or Cookie.
While storing a value in ViewState, it will create a hidden field
in the page and store the value to maintain it across the postback.
public int NextCount
{
get { return ViewState["NextCount"] != null ? (int)ViewState["NextCount"] : 0; }
set { ViewState["NextCount"] = value; }
}
protected void btnNext_Click1(object sender, EventArgs e)
{
NextCount = NextCount+7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
NextCount = NextCount - 7;
lblsum.Text = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(NextCount).ToShortDateString();
}

showing submit query after deleting the image from datalist

I have the following code and some images listed in a DataList:
protected void btnDel_Click(object sender, EventArgs e)
{
if (Id != 0)
{
BaseClass.Delete(Id1);
string path = Path.Combine(GetDirectory(Name), Name);
File.Delete(path);
}
}
public void BindImages()
{
path = BaseClass.GetAllImages(PId);
for (int i = 0; i < path.Count; i++)
{
ArrayList lst = path[i];
tb.Rows.Add(Convert.ToInt32(lst[0]), lst[1].ToString(),
lst[2].ToString(), i);
}
dlst1.DataSource = tb;
dlst1.DataBind();
}
When I click on the delete button for an image the image is removed but when I rebind the DataList the images are being duplicated.
I am binding the DataList in my PageLoad method.
You have to use IsPostBack boolean property in the Page_Load handler.
protected void page_load()
{
if(!IsPostBack)
{
BindImages();
}
}

Read data from SqlDataSource or GridView

I have SqlDataSource and GridView on web form. GridView.DataSourceID = mySqlDataSource.
When I call myGridView.DataBind(), all data successfully bind on the page.
How is it possible to read already got data from mySqlDataSource or myGridView objects as DataTable or DataView? Thanks
The data in the gridview can read by using FindControl property of Gridview control. For example, for reading values set in the Checkbox column in the grid.
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("checkbox1");
//here code for using value captured in chk
}
Provided your data set isn't gigantic, you could store it in the Session, bind your GridView to the Session data, and then re-use the Session data in your other web objects.
Your code would then look something like this (you'll have to forgive any minor inaccuracies -- I'm away from my development box at the moment):
protected override OnInit(object sender, EventArgs e)
{
base.OnInit();
if (Page.IsPostback == false)
{
SetSessionData();
}
//
// Set your GridView, DataTable, DataView, etc. events here.
//
}
void SetSessionData();
{
List<YourDataBoundObject> myDataBoundObject = GetYourDataBoundObject(); // Or Collection<T>, IEnumerable<T>, etc.
Session["data"] = myDataBoundObject;
}
void YourGridView_Load(object sender, EventArgs e)
{
BindYourGridView();
}
void BindYourGridView()
{
YourGridView.DataSource = GetSessionData();
YourGridView.DataBind();
}
List<YourDataBoundObject> GetSessionData()
{
return (List<YourDataBoundObject>) Session["data"];
}
void YourDataTable_Load(object sender, EventArgs e)
{
BindYourDataTable();
}
void BindYourDataTable()
{
YourDataTable.DataSource = GetSessionData();
YourDataTable.DataBind();
}

Control Add PostBack Problem

I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.
So How can I add control ?
Because you must recreate your controls on every postback,
see this article
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page
{
TextBox tb;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tb = new TextBox();
tb.ID = "testtb";
Page.Form.Controls.Add(tb);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//tb.Text will have whatever text the user entered upon postback
}
}
You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.
To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.
Add controls in runtime and save on postback:
int NumberOfControls = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["b1"] = 0;
}
else
{
if ((int)ViewState["b1"] > 0)
{
CreateBtn();
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
NumberOfControls = (int)ViewState["b1"];
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + ++NumberOfControls;
b1.Click +=new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
ViewState["b1"] = NumberOfControls;
}
protected void CreateBtn()
{
for (int i = 0; i < (int)ViewState["b1"];i++)
{
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + i;
b1.Click += new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
}
}
protected void btn11(object sender, System.EventArgs e)
{
Response.Redirect("AboutUs.aspx");
}

Disable a checkbox created at runtime

In my asp.net application i have created checkboxes at runtime. I want to disable the checked checkbox when i click on a button. How do I achieve this? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 12; i++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Groove;
for (int j = 0; j < 18; j++)
{
tc = new TableCell();
tc.BorderStyle = BorderStyle.Groove;
ch = new CheckBox();
tc.Controls.Add(ch);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IDictionaryEnumerator RoleCheckBoxEnumerator = mRoleCheckBoxList.GetEnumerator();
while (RoleCheckBoxEnumerator.MoveNext())
{
CheckBox RoleCheckBox = (CheckBox)RoleCheckBoxEnumerator.Value;
string BoxRoleName = (string)RoleCheckBox.Text;
if (RoleCheckBox.Checked == true)
{
RoleCheckBox.Enabled = false;
break;
}
}
}
One rule-of-thumb while dealing with dynamically generated user controls is that you have to add them to the container on EVERY POSTBACK.
Just modify your code to generate the controls on every postback, and your code will start working like a charm!
EDIT
I am unsure what the ch variable is. I have assumed that its a checkbox. If I am correct, then all you have to do is to modify these lines
if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
to this
//if(!IsPostBack)
{
form1.Controls.Add(ch);
mRoleCheckBoxList.Add("RoleName", ch);
}
EDIT 2
This is the code for generating 10 checkboxes dynamically -
protected void Page_Init(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = new CheckBox();
c.ID = "chk" + i.ToString();
c.Text = "Checkbox " + (i + 1).ToString();
container.Controls.Add(c);
}
}
Check the checkboxes when the page renders on the client side, click the button. This will cause a postback and the checkboxes will be generated again. In the click event of the button, you'll be able to find the checkboxes like this -
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox c = null;
for (int i = 0; i < 10; i++)
{
c = container.FindControl("chk" + i.ToString()) as CheckBox;
//Perform your relevant checks here, and disable the checkbox.
}
}
I hope this is clear.
Maybe
RoleCheckBox.Parent.Controls.Remove(RoleCheckBox);
You are not getting a proper reference to your checkboxes - mRoleCheckBoxList is not mentioned as part of your checkbox creation.
Try the following in your button event handler:
foreach (TableRow row in Table1.Rows)
foreach (TableCell cell in row.Cells)
{
CheckBox check = (CheckBox)cell.Controls[0];
if (check.Checked) check.Enabled = false;
}
Always when creating dynamic controls in .Net create them here:
protected override void CreateChildControls()
{
base.CreateChildControls();
this.CreateDynamicControls();
} //eof method
and in the PostBack find the them either from the event trigger or from a non-dynamic control:
/// <summary>
/// Search for a control within the passed root control by the control id passed as string
/// </summary>
/// <param name="root">the upper control to start to search for</param>
/// <param name="id">the id of the control as string</param>
/// <returns></returns>
public virtual Control FindControlRecursively(Control root, string id)
{
try
{
if (root.ID == id)
{
return root;
} //eof if
foreach (Control c in root.Controls)
{
Control t = this.FindControlRecursively( c, id);
if (t != null)
{
return t;
} //eof if
} //eof foreach
} //eof try
catch (Exception e)
{
return null;
} //eof catch
return null;
} //eof method

Resources